700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > js + html2canvas 实现将div生成图片并保存到本地 自定义图片名。

js + html2canvas 实现将div生成图片并保存到本地 自定义图片名。

时间:2018-10-29 01:26:47

相关推荐

js + html2canvas 实现将div生成图片并保存到本地 自定义图片名。

1. 效果图

2. 实现代码

1)导入html2canvas

① 下载完成后,导入dist文件夹下的html2canvas.js

yarn add html2canvas

② 导入后报错

解决:

打开导入的html2canvas.js

在文件最后一行有//# sourceMappingURL=html2canvas.js.map修改为// /# sourceMappingURL=html2canvas.js.map

2)逻辑实现

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><script src="./html2canvas.js"></script><style>#box {width: 200px;height: 200px;border: 1px solid black;}</style></head><body><div id="box"><div style="height:30px;display: flex;"><div style="text-align:center;width: 70%;line-height: 30px;">标题部分</div><button id="btn">下载</button></div><div style="background-color: rgb(254, 254, 178);height: 150px;"><p>这里是要截图的部分。</p><p>背景颜色是黄色的。</p></div></div><script>// 功能:按钮点击事件btn.onclick = function (e) {// 调用函数获取图片路径let picDom = e.target.parentNode.nextElementSibling // 结构不同会有差别convertToImage(picDom).then(res => {// 将图片下载到本地var x = new XMLHttpRequest();x.open("GET", res, true);x.responseType = 'blob';x.onload = function (e) {var url = window.URL.createObjectURL(x.response)var a = document.createElement('a');a.href = urla.download = '自定义图片名'a.click()}x.send();})}// 功能:生成快照const convertToImage = (container, options = {}) => {// 1. 设置放大倍数const scale = window.devicePixelRatio;// 2. 传入节点原始宽高const _width = container.offsetWidth;const _height = container.offsetHeight;// 3. html2canvas配置项const ops = {_width,_height,useCORS: true,allowTaint: false,};return html2canvas(container, ops).then(canvas => {// 4. 返回图片的二进制数据return canvas.toDataURL("image/png");});}</script></body></html>

3. 实际应用

实际例子

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。