html2canvas,div内容转canvas图片下载

2020-08-28  本文已影响0人  一个想学仙术的菜鸟仔

参考:
https://www.cnblogs.com/ganws/p/11149668.html
https://www.jianshu.com/p/abd9e9c5ba20

使用html2canvas
  npm install --save html2canvas

使用

 import html2canvas from "html2canvas";
 // 内容
<div id="lcode">变成图片</div>
// js
//创建一个新的canvas
    let newCanvas= document.createElement("canvas");
   w = window.getComputedStyle(document.getElementById("lcode")).width
   h= window.getComputedStyle(document.getElementById("lcode")).height
   newCanvas.width = w * 2;
   newCanvas.height = h * 2;
   newCanvas.style.width = w + "px";
   newCanvas.style.height = h + "px";
    let context: any = newCanvas.getContext("2d");
    context.scale(2, 2);
    html2canvas(document.getElementById("lcode") as any, {
      canvas: newCanvas,
    }).then(function(canvas) {
      //canvas转换成url,然后利用a标签的download属性,直接下载
      let a = document.createElement("a");
      a.href = canvas.toDataURL();
      //设置下载文件的名字
      a.download = "下载";
      //点击
      a.click();
    });
上一篇下一篇

猜你喜欢

热点阅读