当前位置:   article > 正文

html元素转化为图片(下载保存)_html转图片

html转图片

1.下载引入html2canvas

npm i html2canvas -save
  1. //printCharts.vue
  2. import html2canvas from "html2canvas";

2.点击按钮下载图片

  1. <button @click="printBtn('.toImg2')"></button>
  2. <div class="toImg2"></div>
  1. // printCharts.vue
  2. async printBtn(img) {
  3. const card = document.querySelector(img); //img 为要下载图片的dom元素
  4. const canvas = await html2canvas(
  5. card,
  6. {
  7. width: 795, //设置canvas的宽度
  8. height: 420, //设置canvas的高度
  9. useCORS: true, // 【重要】开启跨域配置
  10. allowTaint: true, // 允许跨域图片
  11. }
  12. ) // 创建一个临时的a标签
  13. let a = document.createElement("a");
  14. document.body.appendChild(a);
  15. // 为a标签添加属性
  16. a.setAttribute("href", canvas.toDataURL("image/jpg", 1.0)); //toDataUrl:将canvas画布信息转化为base64格式图片
  17. a.setAttribute("download", "text.png"); //导出图片名称
  18. a.setAttribute("target", "_self"); // 在当前窗口中打开
  19. a.click(); // 同时调用a标签的点击事件
  20. // 最后删除该临时节点
  21. document.body.removeChild(a);
  22. },

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/204562
推荐阅读
相关标签
  

闽ICP备14008679号