HTML5 error Canvas access-control-allow-origin

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

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

The canvas is taken from an image filed from another domain, but I use a proxy to add these two lines to the image response header:

access-control-allow-origin: *

access-control-allow-credentials: true

What am I missing?

Thanks,
Ted

+6
source share
1 answer

To make the correct 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; } 

Browser support excludes any known version of IE and unreleased versions of Safari. Firefox and Chrome have many years of support.

+1
source

Source: https://habr.com/ru/post/924601/


All Articles