javascriptinternet-explorercanvastodataurl

Internet Explorer canvas.toDataURL SecurityError


I run the following code on Internet Explorer, it throws a SecurityError on the line var canvasDataUrl = canvas.toDataURL();

var canvas = document.createElement('canvas');
var canvasContext = canvas.getContext('2d');
var img = new Image;
img.onload = function(){
  canvasContext.drawImage(img,0,0);
  var canvasDataUrl = canvas.toDataURL(); // error occurs here
  console.log(canvasDataUrl);
};
img.src = 'https://via.placeholder.com/300x300';

What is the cause of that error, and how can I fix this ?


Solution

  • can you try crossOrigin

    var img = new Image();
    img.crossOrigin = "anonymous";
    

    var canvas = document.createElement('canvas');
    var canvasContext = canvas.getContext('2d');
    var image = new Image();
    image.crossOrigin = "anonymous"; 
    image.onload = function (event) {
        try {
            canvasContext.drawImage(image, 0, 0, 200, 200);
            console.log(canvas.toDataURL());        
        } catch (e) {
            console.log(e);
        }
    };
    image.src = "https://i.chzbgr.com/maxW500/1691290368/h07F7F378/"