Downloading Canvas element to an image
Asked Answered
P

8

96

What are the different ways to save a canvas object?

In my research, I've found two approaches:

var data = canvas.toDataURL();
var prev = window.location.href;
window.location.href = data.replace("image/png", "image/octet-stream");
window.location.href = prev;

Another way is to take a snapshot.

Are there other ways to do this?

Is it possible to customize the download filename?

Poulson answered 14/11, 2011 at 18:55 Comment(0)
I
63

The one way to save is exporting as an image... You already found this solution, and it's the best one i think ;)

    var canvas = document.getElementById("mycanvas");
    var img    = canvas.toDataURL("image/png");
    document.write('<img src="'+img+'"/>');

You can use different image types. Change the mimetype in this function:

    canvas.toDataURL("image/jpeg");

An other way to save canvas data (into a PDF) is using the wkhtmltopdf Library

Cheers. Frank

frankneff.ch / @frankneff

Inflict answered 14/11, 2011 at 19:21 Comment(3)
When I do document.write, wouldn't it just write onto the webpage? Or would that issue a download command?Poulson
Yes it just writes the image onto the page. You can force downloading, but in that case, you'll need a server-side implementation explained here, or google "force image download"Inflict
to download the image you can place it in an <a> tag using download attribute (html5) : <a href="javascript:canvas.toDataURL('image/jpeg');" download="download" >Download as jpeg</a>Indention
L
117

Solution that requires NO BUTTON:

var download = function(){
  var link = document.createElement('a');
  link.download = 'filename.png';
  link.href = document.getElementById('canvas').toDataURL()
  link.click();
}

Useful if you have other triggers for downloading, or triggers that you can't easily reference.

Litalitany answered 11/5, 2018 at 22:9 Comment(3)
@TAHASULTANTEMURI can you be more specific? And in case you found a fix, share it.Litalitany
check the answer , actually toDataURL is not longer effective due to security reason but if you are downloading the image from canvas that was imported from img tag then this tag should have crossorigin attribute to make it work see #20424779Thill
@TAHASULTANTEMURI thanks! can you check if implementing the suggested answer (img.setAttribute('crossOrigin', 'anonymous'); img.src = url) works?Litalitany
I
63

The one way to save is exporting as an image... You already found this solution, and it's the best one i think ;)

    var canvas = document.getElementById("mycanvas");
    var img    = canvas.toDataURL("image/png");
    document.write('<img src="'+img+'"/>');

You can use different image types. Change the mimetype in this function:

    canvas.toDataURL("image/jpeg");

An other way to save canvas data (into a PDF) is using the wkhtmltopdf Library

Cheers. Frank

frankneff.ch / @frankneff

Inflict answered 14/11, 2011 at 19:21 Comment(3)
When I do document.write, wouldn't it just write onto the webpage? Or would that issue a download command?Poulson
Yes it just writes the image onto the page. You can force downloading, but in that case, you'll need a server-side implementation explained here, or google "force image download"Inflict
to download the image you can place it in an <a> tag using download attribute (html5) : <a href="javascript:canvas.toDataURL('image/jpeg');" download="download" >Download as jpeg</a>Indention
B
32

function download() {
var download = document.getElementById("download");
var image = document.getElementById("myCanvas").toDataURL("image/png")
    .replace("image/png", "image/octet-stream");
download.setAttribute("href", image);
//download.setAttribute("download","archive.png");
}
<a id="download" download="triangle.png">
<button type="button" onClick="download()">Download</button>
</a>
    
<canvas id="myCanvas" width="720" height="450">Your browser does not support Canvas.</canvas>
British answered 2/3, 2017 at 3:22 Comment(2)
Can you explain why this is better?Persevering
Yeah, why? Sorry, I can't edit it! The queue is fullSeptarium
L
21

Try something like this...

function downloadCanvasAsImage(){

    let canvasImage = document.getElementById('canvas').toDataURL('image/png');
    
    // this can be used to download any image from webpage to local disk
    let xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function () {
        let a = document.createElement('a');
        a.href = window.URL.createObjectURL(xhr.response);
        a.download = 'image_name.png';
        a.style.display = 'none';
        document.body.appendChild(a);
        a.click();
        a.remove();
      };
      xhr.open('GET', canvasImage); // This is to download the canvas Image
      xhr.send();
}
Lueluebke answered 17/5, 2019 at 11:55 Comment(2)
What if we want to convert it in SVG? Please guide.Threepiece
Canvas is a raster format. SVG is a vector format. You can't just convert between themRubiaceous
C
9
var c = document.getElementById("popup");
var link = document.getElementById('cropImageLink');
link.setAttribute('download', 'MintyPaper.png');
link.setAttribute('href', c.toDataURL("image/png").replace("image/png", "image/octet-stream"));
link.click();

I hope these code would be work. But first create Anchor tag in canvas tag whose id is 'cropImageLink'. than after check. but it's not working in IE browser

Coincidentally answered 5/9, 2014 at 7:40 Comment(0)
S
4

You can use the reimg library to do this really easily.

Converting the canvas to an img : ReImg.fromCanvas(document.getElementById('yourCanvas')).toPng()

And downloading this image for the user can be done like this : ReImg.fromCanvas(document.getElementById('canvas')).downloadPng()

About giving the file a custom name, if you look into the code of the library (which is very short and simple to understand) you'll find that you can change the name.

Here is a link to the specific line: https://github.com/gillyb/reimg/blob/master/reimg.js#L63 filename = filename || 'image.png';

Sturmabteilung answered 1/9, 2015 at 15:39 Comment(0)
T
0

relate to this and thanks to @kaiido

I just modified the callback method and it worked ,the callback method mentioned there was not working for me

var callback = function(blob) {
var a = document.createElement('a');
var saveAs = $('input[name="group1"]:checked').val();


var link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'Image.' + saveAs;
document.body.appendChild(link);
link.click();

};
 function dataURIToBlob(dataURI, callback) {
var binStr = atob(dataURI.split(',')[1]),
len = binStr.length,
arr = new Uint8Array(len);

 for (var i = 0; i < len; i++) {
  arr[i] = binStr.charCodeAt(i);
 }

   callback(new Blob([arr]));
 }
Thill answered 21/1, 2020 at 11:19 Comment(0)
C
-2

Chromium DevTools > Inspect canvas tag > 'Capture node screenshot' and and you can paste it anywhere for a simple and quick review.

Capture node screenshot

Cata answered 24/5, 2022 at 8:18 Comment(1)
This creates a screenshot, doesn't download the canvas elementJordans

© 2022 - 2024 — McMap. All rights reserved.