Question

I have a following problem: when I draw a rectangle (using fillRect method), and then I draw an image (using drawImage), I can't get correct result from Contex, by using getImageData. When I comment line with drawImage, it works correctly. Where is the problem?

var img=document.getElementById("img");
var canvas=document.getElementById("can");
var ctx=canvas.getContext('2d');

ctx.fillStyle="red";
ctx.fillRect(0,0,50,50);
ctx.drawImage(img, 0, 0, 19, 19); //;(

var imgData=ctx.getImageData(0,0,50,50);
ctx.putImageData(imgData,100,100);

Problem: http://jsfiddle.net/yX5mj/1/

Was it helpful?

Solution

If you look in the console, it tells you the error:

Unable to get image data from canvas because the canvas has been tainted
by cross-origin data.

So, it doesn't want to read the data because your image might be malicious. To prevent this, either host the image on your server, or do something like base64 encode the image that you want and embed it in the page.

You can see an example of base64 encoding here, and you can find base64 encoders on the internet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top