0

I'm trying to make a button to capture and save my page in png.

For now, I can duplicate it with the resolution I need, but instead of showing it need to show a dialog and save it like "Save as..." to rename the file.

function myRenderFunction(canvas) {
  destination.appendChild(canvas);
}

var element = document.getElementById('element');
var destination = document.getElementById('destination');



html2canvas(element, {
  scale: 3,
    onrendered: myRenderFunction
});

Here is a JSFiddle of my current process.

Léo Durand
  • 215
  • 1
  • 4
  • 13

1 Answers1

4

To save the image locally you can change your render function to the following:

function myRenderFunction(canvas){
    var a = document.createElement('a');
    // toDataURL defaults to png, so we need to request a jpeg, then convert for file download.
    a.href = canvas.toDataURL("image/jpeg").replace("image/jpeg", "image/octet-stream");
    a.download = 'somefilename.jpg';
    a.click();
}

This is from an answer of stackoverflow How to save img to user's local computer using HTML2canvas

  • I meant a "save as window" where the user can choose the name and the destination of the capture. – Léo Durand Jun 03 '17 at 14:48
  • 1
    The dialog depends on the browser. If on chrome you've set up the downloads folder in the chrome settings, then the file will get downloaded there inmediately without dialog else it will show you the dialog. But this depends entirely on the browser. There are no other options for downloading files with javascript. – Merunas Grincalaitis Jun 03 '17 at 16:31
  • 1
    Thanks, I didn't know that. It does work but it's weird, I have no idea why I can't make it happen with a button. [JSFiddle](https://jsfiddle.net/Leshautsdurant/tvyux7eo/18/) – Léo Durand Jun 03 '17 at 17:05
  • if you want to make it with a button just wrap your `html2canvas(...` content inside a `document.querySelector('#mybutton').addEventListener('click', () => { // put your entire html2canas here });` – Merunas Grincalaitis Jun 03 '17 at 20:19