将HTML内容写入Canvas生成图片
我们使用 html2canvas
话不多说,直接下载
npm i -s html2canvas
<script type="text/javascript" src="html2canvas.js"></script>
例子:
html2canvas(document.getElementById('view'), {
onrendered: function(canvas) {
document.body.appendChild(canvas);
},
});
实现转换成图片
html2canvas(copyDom, {
allowTaint: false,
useCORS: true,
height: targetDom.scrollHeight,
width: targetDom.scrollWidth
}).then(canvas => {
this.printShow = true
copyDom.parentNode.removeChild(copyDom)
canvas.style.width = parseFloat(canvas.style.width) * 0.8 + 'px'
canvas.style.height = parseFloat(canvas.style.height) * 0.8 + 'px'
setTimeout(() => {
const container = document.querySelector('#view')
while (container.hasChildNodes()) {
container.removeChild(container.firstChild)
}
const dataImg = new Image()
dataImg.src = canvas.toDataURL('image/png')
document.querySelector('#view').appendChild(dataImg)
const alink = document.createElement("a");
alink.href = dataImg.src;
alink.download = "testImg.jpg";
alink.click();
}, 0)
});
最好提醒一下, a标签下载长度有限。具体见我下一条博客