CORS Enabled Image

The HTML specification introduces a crossorigin attribute for images that, in combination with appropriate CORS header, allows images defined by the <img> element loaded from foreign origins to be used in canvas as if they were being loaded from the current origin.

See CORS settings attributes for details on how the crossorigin attribute is used.

What is a "tainted" canvas?

Although you can use images without CORS approval in your canvas, doing so taints the canvas. Once a canvas has been tainted, you can no longer pull data back out of the canvas. For example, you can no longer use the canvas toBlob(), toDataURL(), or getImageData() methods; doing so will throw a security error.

This protects users from having private data exposed by using images to pull information from remote web sites without permission.

Example: Storing an image from a foreign origin

Provided that you have a server hosting images along with appropriate Access-Control-Allow-Origin header, you will be able to save those images to localStorage as if they were served from your domain.

var img = new Image,
    canvas = document.createElement("canvas"),
    ctx = canvas.getContext("2d"),
    src = "http://example.com/image"; // insert image url here

img.crossOrigin = "Anonymous";

img.onload = function() {
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage( img, 0, 0 );
    localStorage.setItem( "savedImageData", canvas.toDataURL("image/png") );
}
img.src = src;
// make sure the load event fires for cached images too
if ( img.complete || img.complete === undefined ) {
    img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
    img.src = src;
}

Browser compatibility

  • Desktop
  • Mobile

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 13 8 -- -- Nightly build
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? ? ? ? ?

Tags (3)

Edit tags

Attachments (0)

 

Attach file