Allow cross-origin images on canvas

11 minutes to integrate

You’d probably like to use images from the Uploadcare CDN on HTML canvas. Unfortunately, browsers restrict access to canvas if an image is downloaded from an untrusted source.

By default, only images of the same origin are treated as trusted. If you draw images from other origins, the canvas will automatically be marked as "tainted", which is considered a security risk by browsers. Any attempt to read or export such a canvas element will result in an error.

For instance, calling getImageData() or toDataURL() will lead to a SecurityError:

canvas.toDataURL();
// Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
canvas.getContext('2d').getImageData(0, 0, 100, 100);
// Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.javascript

You need to make a CORS request.

img crossorigin

One of the solutions is to use the crossorigin image attribute that will determine if the image should be fetched using a CORS request. This attribute is currently supported by most browsers. Use anonymous or an empty default “” value to send a request with credentials omitted, or a use-credentials value to include credentials: cookies, X.509 certificates, and the Authorization request header. Below is an example that contains an anonymous CORS request.

XMLHttpRequest

Another way to make a CORS request is to fetch the image using an XMLHttpRequest object. This is probably something you use a lot if you’re into AJAX. It retrieves data from a URL without having to do a full page refresh.