原始图像数据转换在javascript

Raw image data conversion in javascript

本文关键字:javascript 转换 数据 图像 原始      更新时间:2023-09-26

我从服务器获得原始图像数据,在画布上绘制它的最佳选择是什么,我该如何做到这一点?请给我一个见解,因为我是非常新的html和javascript。如果我知道原始图像的宽度和高度,我想知道的是如何转换原始数据并在html和javascript的画布上绘制它。基本上我不知道原始图像的格式,我需要做一些转换。

你可以使用context.createImageData创建一个imageData对象,你可以用你的RGBA数据从你的服务器:

示例代码和演示: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);