Search code examples
javascriptjqueryhtml2canvas

html2canvas saving canvas images with extension


I have a web page with button onclick on that button a screenshot of this page should be taken and downloaded with (.jpg) extension. to do that I use the following code:

$("#Finish").on('click', function () {
// take a screenshot and save it.
html2canvas(element, {
	onrendered: function (canvas) {
		$("#previewImage").append(canvas);
		getCanvas = canvas;
	   DownloadImage();
	}
});
});

function DownloadImage() {
var imageData = getCanvas.toDataURL("image/png"); 
var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
   window.open(newData);
}

when i click the button:

show image

As you see I have image with "download" Name without any extension. I need to download the image with specific name and extension for example "myImage.jpg"


Solution

  • If you can change the button into a <a> tag, you should be able to use the download attribute.

    $('#image-link').attr('href', 'data:image/png;base64,<data>").attr('download', 'filename.png');
    

    Haven't played around with it too much myself but it is said to work in Firefox, Chrome and Edge: https://caniuse.com/#feat=download