Question

I have this function to turn canvas content into PNG data.

function saveImage()
{
    var img = canvas.toDataURL("image/png");
    var imgWin = window.open('','', 'width=880, height=720');

    imgWin.document.write('<!doctype html><html><head></head>' +
            '<body> <img src="' + img +'" alt=""/> </body> </html>');   
}

Works like a charm and puts the png right on screen just like it should be. Now I can easily drag and drop it to the desktop in Chrome.

But with Firefox I end up with a link, and in IE (which I don't really care to support with the application I' building) it won't drag at all.

I understand this has to do with how the browsers handle DataURL's. But is there a way to turn this DataURL-png in to a real image, that is saved to cache or some other place from where I can read it?

So this

var img = canvas.toDataURL("image/png");
<img src="' + img +'" alt=""/>

will turn into something like:

var img = canvas.toDataURL("image/png");
img.goNinjaAndTurnIntoRealPng()
<img src="../local/img.png" alt=""/>
Was it helpful?

Solution

Your goNinjaAndTurnIntoRealPng() approach only works if you send the image data to the server and save it there (in order to get a path like "../local/img.png") - depends on your application if that makes sense.

If you just want to enable users to directly download the canvas as PNG, you could trigger the image download as follows. Personally, I prefer this approach because users don't have to manually click "save as" - it's a lot more usable.

<canvas id="canvas" width="880" height="720"></canvas><br>
<!-- Note the "download" attribute here that specifies a filename -->
<a download="canvas_image.png" id="click">Save PNG image</a>

<script>
    var canvas = document.getElementById("canvas");
    document.getElementById("click").onclick = function(){
        this.href = canvas.toDataURL("image/png");
    };
</script>

Demo (JSFiddle) (tested in Firefox and Chrome)

Also see this question which provides some more info.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top