How To Save Canvas As An Image With canvas.toDataURL()?

JavascriptHtmlCordovaCanvasSave

Javascript Problem Overview


I'm currently building a HTML5 web app/Phonegap native app and I can't seem to figure out how to save my canvas as an image with canvas.toDataURL(). Can somebody help me out?

Here's the code, what's wrong with it?

//My canvas was named "canvasSignature"

JavaScript:


function putImage()
{
  var canvas1 = document.getElementById("canvasSignature");        
  if (canvas1.getContext) {
 	 var ctx = canvas1.getContext("2d");                
     var myImage = canvas1.toDataURL("image/png");      
  }
  var imageElement = document.getElementById("MyPix");  
  imageElement.src = myImage;                           
  
}  

HTML5:


<div id="createPNGButton">
    <button onclick="putImage()">Save as Image</button>        
</div>

Javascript Solutions


Solution 1 - Javascript

Here is some code. without any error.

var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");  // here is the most important part because if you dont replace you will get a DOM 18 exception.


window.location.href=image; // it will save locally

Solution 2 - Javascript

This solution allows you to change the name of the downloaded file:

HTML:

<a id="link"></a>

JAVASCRIPT:

  var link = document.getElementById('link');
  link.setAttribute('download', 'MintyPaper.png');
  link.setAttribute('href', canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"));
  link.click();

Solution 3 - Javascript

You can try this; create a dummy HTML anchor, and download the image from there like...

// Convert canvas to image
document.getElementById('btn-download').addEventListener("click", function(e) {
    var canvas = document.querySelector('#my-canvas');

    var dataURL = canvas.toDataURL("image/jpeg", 1.0);

    downloadImage(dataURL, 'my-canvas.jpeg');
});

// Save | Download image
function downloadImage(data, filename = 'untitled.jpeg') {
    var a = document.createElement('a');
    a.href = data;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
}

Solution 4 - Javascript

You can use canvas2image to prompt for download.

I had the same issue, here's a simple example that both adds the image to the page and forces the browser to download it:

<html>
	<head>
		<script src="http://hongru.github.io/proj/canvas2image/canvas2image.js"></script>
		<script>
			function draw(){
				var canvas = document.getElementById("thecanvas");
				var ctx = canvas.getContext("2d");
				ctx.fillStyle = "rgba(125, 46, 138, 0.5)";
				ctx.fillRect(25,25,100,100); 
				ctx.fillStyle = "rgba( 0, 146, 38, 0.5)";
				ctx.fillRect(58, 74, 125, 100);
			}
			
			function to_image(){
				var canvas = document.getElementById("thecanvas");
				document.getElementById("theimage").src = canvas.toDataURL();
				Canvas2Image.saveAsPNG(canvas);
			}
		</script>
	</head>
	<body onload="draw()">
		<canvas width=200 height=200 id="thecanvas"></canvas>
		<div><button onclick="to_image()">Draw to Image</button></div>
		<image id="theimage"></image>
	</body>
</html>

Solution 5 - Javascript

I created a small library that does this (along with some other handy conversions). It's called reimg, and it's really simple to use.

ReImg.fromCanvas(yourCanvasElement).toPng()

Solution 6 - Javascript

Similar to 1000Bugy's answer but simpler because you don't have to make an anchor on the fly and dispatch a click event manually (plus an IE fix).

If you make your download button an anchor you can highjack it right before the default anchor functionality is run. So onAnchorClick you can set the anchor href to the canvas base64 image and the anchor download attribute to whatever you want to name your image.

This does not work in (the current) IE because it doesn't implement the download attribute and prevents download of data uris. But this can be fixed by using window.navigator.msSaveBlob instead.

So your anchor click event handler would be as followed (where anchor, canvas and fileName are scope lookups):

function onClickAnchor(e) {
  if (window.navigator.msSaveBlob) {
    window.navigator.msSaveBlob(canvas.msToBlob(), fileName);
    e.preventDefault();
  } else {
    anchor.setAttribute('download', fileName);
    anchor.setAttribute('href', canvas.toDataURL());
  }
}

Here's a fiddle

Solution 7 - Javascript

This work for me: (Only google chrome)

<html>
<head>
    <script>
            function draw(){
                var canvas = document.getElementById("thecanvas");
                var ctx = canvas.getContext("2d");
                ctx.fillStyle = "rgba(125, 46, 138, 0.5)";
                ctx.fillRect(25,25,100,100);
                ctx.fillStyle = "rgba( 0, 146, 38, 0.5)";
                ctx.fillRect(58, 74, 125, 100);
            }

            function downloadImage()
            {
                var canvas = document.getElementById("thecanvas");
                var image = canvas.toDataURL();

                var aLink = document.createElement('a');
                var evt = document.createEvent("HTMLEvents");
                evt.initEvent("click");
                aLink.download = 'image.png';
                aLink.href = image;
                aLink.dispatchEvent(evt);
            }
    </script>
</head>
<body onload="draw()">
    <canvas width=200 height=200 id="thecanvas"></canvas>
    <div><button onclick="downloadImage()">Download</button></div>
    <image id="theimage"></image>
</body>
</html>

Solution 8 - Javascript

Instead of imageElement.src = myImage; you should use window.location = myImage;

And even after that the browser will display the image itself. You can right click and use "Save Link" for downloading the image.

Check this link for more information.

Solution 9 - Javascript

You cannot use the methods previously mentioned to download an image when running in Cordova. You will need to use the Cordova File Plugin. This will allow you to pick where to save it and leverage different persistence settings. Details here: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/

Alternatively, you can convert the image to base64 then store the string in localStorage but this will fill your quota pretty quickly if you have many images or high-res.

Solution 10 - Javascript

i create simple typescript function for this purpose, just delete types to use with javascript.

 //ImagePath == canvas.toDataUrl()
private saveImage(imagePath: string, imageName: string ){
    const link = document.createElement('a');
    link.style.display = 'none';
    document.body.appendChild(link)
    link.setAttribute('download', imageName + '.png');
    link.setAttribute('href', imagePath.replace("image/png", "image/octet-stream"));
    link.click();
}

 //function call
 saveImage(canvas.toDataURL(), "myName")

Solution 11 - Javascript

One can also use element reference to downloaded image:

HTML:

<a download style="display:none" ref="imageDownloadRef"></a>

JAVASCRIPT:

  this.$refs['imageDownloadRef'].href = this.canvas.toDataURL({
  format: 'jpeg',
  quality: 1.0,
  })
  const imageDownloadLink = this.$refs.imageDownloadRef as HTMLElement
  imageDownloadLink.click()

Solution 12 - Javascript

@Wardenclyffe and @SColvin, you both are trying to save image using the canvas, not by using canvas's context. both you should try to ctx.toDataURL(); Try This:

var canvas1 = document.getElementById("yourCanvasId");  <br>
var ctx = canvas1.getContext("2d");<br>
var img = new Image();<br>
img.src = ctx.toDataURL('image/png');<br>
ctx.drawImage(img,200,150);<br>

Also you may refer to following links:

http://tutorials.jenkov.com/html5-canvas/todataurl.html

http://www.w3.org/TR/2012/WD-html5-author-20120329/the-canvas-element.html#the-canvas-element

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWardenclyffeView Question on Stackoverflow
Solution 1 - Javascriptuser1874941View Answer on Stackoverflow
Solution 2 - JavascriptThomas WagenaarView Answer on Stackoverflow
Solution 3 - JavascriptbmatovuView Answer on Stackoverflow
Solution 4 - JavascriptSColvinView Answer on Stackoverflow
Solution 5 - JavascriptgillybView Answer on Stackoverflow
Solution 6 - JavascriptSjeitiView Answer on Stackoverflow
Solution 7 - Javascript1000BugyView Answer on Stackoverflow
Solution 8 - JavascriptHakan SerceView Answer on Stackoverflow
Solution 9 - JavascriptBigBalliView Answer on Stackoverflow
Solution 10 - JavascriptVít ZadinaView Answer on Stackoverflow
Solution 11 - JavascriptYogesh YadavView Answer on Stackoverflow
Solution 12 - JavascriptVinay ChandraView Answer on Stackoverflow