tags:

views:

247

answers:

3

I load an external image and draw it on the Canvas element like so:

var canvas = document.getElementById('canvas1');
var context = canvas.getContext('2d');
var image = new Image();
image.onload = function(evt) { context.drawImage(evt.target, 0, 0); }
image.src = "test.jpg";

But I want to get the ImageData. So after calling context.drawImage, I do this:

var imagedata = canvas.getImageData();
manipulate(imagedata); // modifies imagedata.data
context.putImageData(imagedata, 0, 0);

Is that the only way to get the imageData of an externally loaded image? Drawing the image on canvas & then getting the imagedata seems awfully slow. Am I missing something?

Thanks!

A: 

You can try doing binary Ajax then decoding the image data manually, but using canvas would be easier.

Jeffery To
A: 

Follow up question,

If you put your image on a canvaswith the intention to grab the pixeldata and modify it, what if you have and image with full or semi transparency in there, that information probably gets lost while drawing the image onto what ever color the canvas has ? I am asking because i am trying to figure out the best way to tint an image before its drawn, i have a question about that here:

http://stackoverflow.com/questions/2688961/how-do-i-tint-an-image-with-html5-canvas

djdolber
+1  A: 

There is no direct way of getting the ImageData, it is inefficient but on the other hand you probably don't need to repeatedly draw the image to a canvas -- if you need the raw data multiple times you probably just want draw to an off screen canvas once and keep that canvas around.

Alas the other problem with canvas is that for security reasons you aren't able to read ImageData from a canvas if you've ever drawn an image (or other resource) from a different origin.

olliej