我想在代码中创建一个新的 ImageData 对象.如果我有一个 Uint8ClampedArray
我想从中制作一个图像对象,那么最好的方法是什么?
I want to create a new ImageData object in code. If I have a Uint8ClampedArray
out of which I want to make an image object, what is the best way to do it?
我想我可以创建一个新的 canvas 元素,提取它的 ImageData 并覆盖它的 data 属性,但这似乎是一种错误的方法.
I guess I could make a new canvas element, extract its ImageData and overwrite its data attribute, but that seems like a wrong approach.
如果我可以直接使用 ImageData 构造函数,那就太好了,但我不知道该怎么做.
It would be great if I could use the ImageData constructor directly, but I can't figure out how to.
这是个有趣的问题...你不能只创建 ImageData
对象:
This is interesting problem... You can't just create ImageData
object:
var test = new ImageData(); // TypeError: Illegal constructor
我也试过了:
var imageData= context.createImageData(width, height);
imageData.data = mydata; // TypeError: Cannot assign to read only property 'data' of #<ImageData>
但如 MDN data
属性是只读的.
but as described in MDN data
property is readonly.
所以我认为唯一的方法是通过迭代创建对象并设置数据属性:
So I think the only way is to create object and set data property with iteration:
var canvas = document.createElement('canvas');
var imageData = canvas.getContext('2d').createImageData(width, height);
for(var i = 0; i < myData.length; i++){
imageData.data[i] = myData[i];
}
更新:我在ImageData的data
属性中发现了set
方法,所以解决方法很简单:
Update:
I have discovered the set
method in data
property of ImageData, so solution is very simple:
var canvas = document.createElement('canvas');
var imageData = canvas.getContext('2d').createImageData(width, height);
imageData.data.set(myData);
这篇关于如何独立创建新的 ImageData 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!