Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 530
Ted Smith Avatar asked Sep 05 '12 01:09

Ted Smith


1 Answers

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.

like image 92
Brigand Avatar answered Sep 23 '22 10:09

Brigand