0

I am converting part of the html elements into canvas and converting that into png image. It is working fine but the problem is at the first click it is not converting the html to convas and canvas to png. //HTML To Image on button click

$("#btn-Convert-Html2Image").on('click', function () {
html2canvas(element, {
  onrendered: function (canvas) {
    getCanvas = canvas;
  }
});
setTimeout(function() {
    var imgageData = getCanvas.toDataURL("image/png");
    var newData = imgageData.replace(/^data:image\/png/, "data:application/octet-stream");
    $("#btn-Convert-Html2Image").attr("download", "your_pic_name.png").attr("href", newData);
},400)

    });

Is that anything done wrong. Please see the fiddle link

htoniv
  • 1,658
  • 21
  • 40

2 Answers2

1

At first click you are binding png dataURL to #btn-Convert-Html2Image anchor and when 2nd time you click on this link already bound data is downloaded you can use this approach to overcome this issue.

function downloadURI(uri, name) {
  var link = document.createElement("a");
  link.download = name;
  link.href = uri;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  delete link;
}


$("#btn-Convert-Html2Image").on('click', function () {
  html2canvas(element, {
    onrendered: function (canvas) {
      var imgageData = canvas.toDataURL("image/png");
      var newData = imgageData.replace(/^data:image\/png/, "data:application/octet-stream");
      downloadURI(newData,"your_pic_name.png");
    }
  });
});

JSFiddle link

Rehan Haider
  • 893
  • 11
  • 26
1

Good news: You make everthing right!

The last line of code says : Set the atribute of the download button to your image. Thast good but to late. You have already clicked the button. So wehn you click the button again the image from the last run will be downloaded and a new one will be generated and linked to the button.

You simply have to force the download AFTER you have generated the image. For example by forcing a URI download ...

Marcus
  • 1,910
  • 2
  • 16
  • 27