pa-2uw
Last Updated: February 25, 2016
·
11.86K
· travm
Df24f646d6270b14d6f18e39f9a755bb

Using external images with canvas' getImageData() and toDataURL()

Dealing with external cross-domain resources can be a major frustration when manipulating images in canvas.

However, there is a very simple solution to avoid all the crazy security errors that a browser may throw at you.

You simply need to set the .crossOrigin canvas method to an empty string.

Like so:

img.crossOrigin = '';

And some example code:

var img = document.createElement('img');
img.onload = function(e) {
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    var url = canvas.toDataURL(); // Read succeeds, canvas won't be dirty.
};
img.crossOrigin = '';
img.src = 'http://other-domain.com/image.jpg';

(Note: The website you are pulling the image from must support the CORS spec.)

References:

Say Thanks
Respond

1 Response
Add your response

11931
Edd84d4d307561dde0665080c6398847

Hi Travis,

This has been working pretty sweetly in Chrome(/Chromium) and Firefox but when using IE10 it throws security erros. Would you know of any work around? I have been trying a bit with some normal xhr requests. But to no avail.

Cheers,

Fritz

over 1 year ago ·