Programmers learn & share
0 votes
99 views

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?

by (6.9k points)   | 99 views

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

        </FilesMatch>

    </IfModule>

</IfModule>

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.

by (36.1k points)  
2,245 questions
2,807 answers
60 comments
241 users