Last Updated: February 25, 2016
· travm

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

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


1 Response
Add your response

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.



over 1 year ago ·