简体   繁体   English

单击初始按钮时将HTML转换为png图像

[英]converting from html to png image on initial button click

I am converting part of the html elements into canvas and converting that into png image. 我将html元素的一部分转换为画布,并将其转换为png图像。 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转换为convas,将画布转换为png。 //HTML To Image on button click // HTML To Image on button单击

$("#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 请查看小提琴链接

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. 第一次单击时,您将png dataURL绑定到#btn-Convert-Html2Image锚点,当第二次单击此链接时,已经下载了已绑定的数据,则可以使用此方法来解决此问题。

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 JSFiddle链接

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 ... 例如,通过强制URI下载...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM