html转图片

将HTML内容写入Canvas生成图片

我们使用 html2canvas

话不多说,直接下载

// 1、 npm 下载
npm i -s html2canvas

// 2、 html 引入
<script type="text/javascript" src="html2canvas.js"></script>

// 二者选其一
例子:
// 这个是上面引入的方法 html2canvas
// document.getElementById('view') // 选择要被转换的dom
html2canvas(document.getElementById('view'), {
        onrendered: function(canvas) {
            // 转换好的回调函数
            document.body.appendChild(canvas);
        },
      // width: 300,
      // height: 300
    });
实现转换成图片
// 里面注意将不需要的部分删了
html2canvas(copyDom, {
    				// 截屏区域有跨域图片
                    allowTaint: false,
                    useCORS: true,
    				// 滚动截屏
                    height: targetDom.scrollHeight,
                    width: targetDom.scrollWidth
                }).then(canvas => {
                    this.printShow = true
                    copyDom.parentNode.removeChild(copyDom)
                    // console.log(canvas.style.width)
                    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)
                        }
                        // toImage
                        const dataImg = new Image()
                        // 获取到 二进制图片数据
                        dataImg.src = canvas.toDataURL('image/png')
                        document.querySelector('#view').appendChild(dataImg)
						// 使用a标签下载
                        const alink = document.createElement("a");
                        alink.href = dataImg.src;
                        alink.download = "testImg.jpg";
                        alink.click();
                    }, 0)
                });
最好提醒一下, a标签下载长度有限。具体见我下一条博客
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

厚渡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值