Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
136
rated 0 times [  141] [ 5]  / answers: 1 / hits: 19756  / 12 Years ago, thu, november 29, 2012, 12:00:00

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.


More From » canvas

 Answers
103

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

[#81722] Wednesday, November 28, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryankiah

Total Points: 183
Total Questions: 99
Total Answers: 112

Location: Christmas Island
Member since Mon, Oct 19, 2020
4 Years ago
;