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 = '';
image.onload = function() {


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

    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?



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 = '';

or in HTML:

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

Make sure you put the img.setAttribute('crossOrigin', ''); before you set the source of your image object. just like this:

var img = document.createElement("img");
//fix crossorigin here...
img.setAttribute('crossOrigin', '');
//after that put your source
img.src = imageSrcURL;


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.