Shaun314 Shaun314 - 7 months ago 72
Javascript Question

getImageData cross-origin error

Precursor: I know there have been a few questions already asked about this topic, but none of them seem to offer a straight JavaScript only solution.

So I ran into this error where I am trying to get the pixel data from a canvas using something like

context.getImageData()
, my exact code can been seen here or below:

<canvas id="imageCanvas" width="600" height="800"></canvas>


// Load Image
var canvas = document.getElementById('imageCanvas');

var image = new Image();
image.src = 'http://emoticons.pw/emoticons/emoticon-faces-002-medium.png';
image.onload = function() {

width=image.width;
height=image.height;

var context = canvas.getContext('2d');
context.fillStyle="#024359"; // canvas background color
context.fillRect(0, 0, width, height);
context.drawImage(this,0,0);

imageData = context.getImageData(0,0,width, height); // PROBLEM HERE

context.putImageData(imageData, 0, 0);
}


I get the following errors in Chrome:


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


and then a security error as well. I don't want to make server changes or start chrome with a weird instruction thing. I feel like there has to be something I can do in JavaScript.

Using local images only is not a problem, but when trying that, I got the same error!

I am trying to do this without a server, if I put this on my "default" godaddy web server, are all my problems solved? I heard rumors dropbox could also simulate a server close enough?

K3N K3N
Answer

You can't use file:// if you're using that (Chrome allow you to override this but I won't recommend it).

For local testing use a light-weight server such as Mongoose which allow you use http://localhost as a domain to test your local pages. This way you avoid problems with CORS.

If you need to host images on a different domain you need to make sure they support cross-origin usage.

DropBox and ImgUrl (I recommend the latter for just images) both support CORS usage, but you need to request such usage by adding the crossOrigin property to your image before setting the source (or include it in the HTML tag if you're using that):

var img = new Image;

img.onload = myLoader;
img.crossOrigin = '';              ///=anonymous
img.src = 'http://imgur.com/....';

or in HTML:

<img src="..." alt="" crossOrigin="anonymous" />
Comments