JavaScript中的原始图像数据转换 [英] Raw image data conversion in javascript
问题描述
我从服务器获取原始图像数据,将其绘制在画布上的最佳选择是什么,我该怎么做?请提供一个见解,因为我是html和javascript的新手.我想知道的是,如果我知道原始图像的宽度和高度,我该如何转换原始数据并将其绘制在html和javascript的画布上.基本上我不知道我需要做的原始图像的格式一些转换.
I get a raw image data from a server, what are my best options to draw it on a canvas and how do I do it? Please give an insight as I am very new to html and javascript. All I want to know is how do I convert the raw data and draw it on a canvas in html and javascript, if I know the width and height of the raw image.Basically I dont know the format of the raw image i need to do some conversion.
推荐答案
您可以使用 context.createImageData
创建一个imageData对象,您可以用服务器中的RGBA数据填充该对象:
You can use context.createImageData
to create an imageData object which you can fill with your RGBA data from your server:
示例代码和演示: http://jsfiddle.net/m1erickson/XTATB/
// test data fill a 30x20 canvas with red pixels
// test width/height is 30x20
var canvasWidth=30;
var canvasHeight=20;
// resize the canvas
canvas.width=canvasWidth;
canvas.height=canvasHeight;
// create some test data (you can use server data in production)
var d=[];
for(var i=0;i<canvasWidth*canvasHeight;i++){
// red & alpha=255 green & blue = 0
d.push(255,0,0,255);
}
// create a new imageData object with the specified dimensions
var imgData=ctx.createImageData(canvasWidth,canvasHeight);
// get the data property of the imageData object
// this is an array that will be filled with the test data
var data=imgData.data;
// copy the test data (d) into the imageData.data (data)
for(var i=0;i<data.length;i++){
data[i]=d[i];
}
// push the modified imageData object back to the canvas
ctx.putImageData(imgData,0,0);
这篇关于JavaScript中的原始图像数据转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!