Ted Smith
Ted Smith

Reputation: 63

HTML5 Canvas access-control-allow-origin error

I'm getting the following javascript error when I try to get data from a canvas element:

Error: canvas.toDataURL() not supported. [Exception... "The operation is insecure." code: "18" nsresult: "0x80530012 (SecurityError)"...

The canvas is drawn from an image served from a different domain, but I'm using a proxy to add these 2 lines to the image response header:

access-control-allow-origin: *

access-control-allow-credentials: true

What am I missing?

Thanks,
Ted

Upvotes: 6

Views: 4788

Answers (1)

Brigand
Brigand

Reputation: 86220

To make a proper CORS request, you must set the image's cross origin property to "Anonymous". This example is from the Mozilla Developer Network.

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;
}

The browser support excludes any known version of IE, and unreleased versions of Safari. Firefox and Chrome have years of support.

Upvotes: 1

Related Questions