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:
Written by Travis Maynard
Related protips
1 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.
Cheers,
Fritz
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside