Search code examples
html2canvas

How to Set Size of Rendered Image


I'm confused with how to designate the size of the image that html2canvas generates. For example, I'd like to be able to have my DIV remain 400px x 400px but have the rendered image be 1200px x 1200px. I've looked at the documentation but I'm misunderstanding how to apply it. I've tried adding a.width: 1200; a.height: 1200; without luck.

What am I doing wrong?

My save function, from my JS:

$('#save').click(function() {
  html2canvas($('#imagesave'), {
    onrendered: function(canvas) {
      var a = document.createElement('a');
      a.href = canvas.toDataURL("image/png");
      a.download = 'myfile.png';
      a.click();
    }
  });
});

HTML

<div id="imagesave">
...
</div>

<button id="save">Save</button>

CSS

#imagesave {
  background-color: white;
  height: 400px;
  width: 400px;
}

Solution

  • html2canvas($('#imagesave')[0], {
      width: 1200,
      height: 1200
    }).then(function(canvas) {
      var a = document.createElement('a');
      a.href = canvas.toDataURL("image/png");
      a.download = 'myfile.png';
      a.click();
    });
    

    You need to pass width and height as options to html2canvas as mentioned in docs. Here is the fiddle for the same.

    html2canvas($('#imagesave')[0], {
      scale:3
    }).then(function(canvas) {
      var a = document.createElement('a');
      a.href = canvas.toDataURL("image/png");
      a.download = 'myfile.png';
      a.click();
    });
    

    you can scale using scale attribute, which will scale horizontally and vertically with that much times.