• Register
0 votes

Problem :

I want to save my canvas to a img. I have this function:

function save() {
    document.getElementById("canvasimg").style.border = "2px solid";
    var dataURL = canvas.toDataURL();
    document.getElementById("canvasimg").src = dataURL;
    document.getElementById("canvasimg").style.display = "inline";

It gives me error:

Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

What should I do?

6.9k points

1 Answer

0 votes

Solution :

I had faced similar issue recently. I did lot research and found the following solution to the issue:

You must have a server which should be hosting images with the appropriate Access-Control-Allow-Origin header.

<IfModule mod_setenvif.c>

    <IfModule mod_headers.c>

        <FilesMatch "\.(cur|gif|ico|jpe?g|png|svgz?|webp)$">

            SetEnvIf Origin ":" IS_CORS

            Header set Access-Control-Allow-Origin "*" env=IS_CORS




You can save those images to DOM Storage as if they were served from your domain otherwise you may run into security issue.

var img = new Image,

    canvas = document.createElement("canvas"),

    ctx = canvas.getContext("2d"),

    src = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"; // 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;


If you follow above procedure then your issue will be resolved.

36.1k points

Related questions

0 votes
1 answer 557 views
Problem : Facing following javascript issue failed to execute 'removechild' on 'node': the node to be removed is not a child of this node.
asked Nov 14, 2019 peterlaw 6.9k points
0 votes
1 answer 530 views
Problem : I want to drag and drop the image on the div. The image does not get dragged onto a div and gives the below error : Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.draganddrop.html:20 dropdraganddrop.html:26 ondrop
asked Jan 18 jwilliam 3.9k points
1 vote
1 answer 242 views
Problem : Trying to drag and drop an image on a div. but the image does not get dragged on to the div and gives the following error: uncaught typeerror: failed to execute 'appendchild' on 'node': parameter 1 is not of type 'node'.
asked Nov 11, 2019 peterlaw 6.9k points