Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

javascript - How to create a new ImageData object independently?

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?

I guess I could make a new canvas element, extract its ImageData and overwrite its data attribute, but that seems like a wrong approach.

It would be great if I could use the ImageData constructor directly, but I can't figure out how to.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is interesting problem... You can't just create ImageData object:

var test = new ImageData(); // TypeError: Illegal constructor

I have also tried:

var imageData= context.createImageData(width, height);
imageData.data = mydata; // TypeError: Cannot assign to read only property 'data' of #<ImageData> 

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];
}

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...