我有一系列构建rgba序列数组的函数,我计划将这些数据应用于画布对象。我不确定如何将rgba(已经在0-255值中)转换为适当的imageData对象,我可以使用.putImageData。
var new_canvas = document.createElement('canvas');
var mc_ctx = new_canvas.getContext('2d');
new_canvas.width = 50;
new_canvas.height = 50;
var mc_imageData = mc_ctx.getImageData(0,0, 50, 50);
var mc_px_data = mc_imageData.data;
for ( var i = 0; i <= rgba_array.length; i++ ) {
mc_px_data[i] = rgba_array[i];
}
mc_ctx.putImageData(mc_imageData, 0, 0);
我得到的只是白色,即使rgba_array值的输出显示正确的值流。
答案 0 :(得分:1)
在mc_px_data
中设置值后,必须将其转换为UInt8ClampedArray
并正确设置数据或不会写入数据。以下内容应在for loop
(未经测试)
var new_canvas = document.createElement('canvas');
var mc_ctx = new_canvas.getContext('2d');
new_canvas.width = 50;
new_canvas.height = 50;
var mc_imageData = mc_ctx.getImageData(0,0, 50, 50);
var mc_px_data = mc_imageData.data;
for ( var i = 0; i <= rgba_array.length; i++ ) {
mc_px_data[i] = rgba_array[i];
}
// New code here:
mc_px_data = new Uint8ClampedArray(mc_px_data);
mc_imageData.data.set(mc_px_data);
mc_ctx.putImageData(mc_imageData, 0, 0);