安装:yarn add html2canvas
引用:
import html2canvas from 'html2canvas';
使用:
//导出图片 printOut(name) { let dom = document.querySelector('#main'); let img = document.querySelector('#watermark'); html2canvas(dom, { useCORS: true, //支持图片跨域 scale: 1, //设置放大的倍数
// 页面有滚动条时设置,若不加导出图片为当前可视区域 height: document.getElementById('main').scrollHeight, windowHeight: document.getElementById('main').scrollHeight, backgroundColor:null }).then((canvas) => {
//添加水印 let ctx = canvas.getContext("2d"); const water = document.createElement('canvas'); water.width=260; water.height=300; const waterCtx = water.getContext("2d"); waterCtx.drawImage(img, 30, 60); const pat = ctx.createPattern(water,'repeat'); ctx.fillStyle=pat; ctx.fillRect(0,0,canvas.width,canvas.height) // 生成图片导出 const a = document.createElement('a'); a.href = canvas.toDataURL('image/png'); a.download = name; a.click(); }) },
var img = new Image();
//引入图片地址
img.src = "img/watermark.jpg"
img.onload = function () {
var context = canvas.getContext("2d");
context.drawImage(img, 0, 0);
}
此处水印是图片,使用图片地址(如上方式)一直不成功,所以使用了dom 的方式,添加在页面内隐藏
大佬有解决方案的话,欢迎留言指正