今天是一个发文的好日子😀~
👇👇👇
一个需求,要截取页面中的内容并截图保存,来看一看我是怎么实现的吧:
这里需要使用到插件--html2canvas
1.安装并引入html2canvas
npm install html2canvas
import html2canvasfrom 'html2canvas'
也可以从这里找到相应的文件html2canvas.hertzen.com/dist/html2canvas.js
以便原生js引入
<script type="text/javascript" src=".\html2canvas.js">script>
2.创建(下载按钮)点击事件:
(1)html2canvas方法来获取canvas对象,其第一个参为对应的节点,第二个是相关配置项。
(2)获取到canvas后用其toDataURL方法转换为url,并提供a链接的href(放链接)与download(文件名)并添加到页面上来进行下载(注意图片格式统一)。
(3)想要自动下载,可先将a链接藏起来,并异步使用dispatchEvent触发其点击事件,最后移除该a链接即可。
以上三步代码示例如下👇
- let aimPart = document.querySelector('.app');
- html2canvas(aimPart,{
- scale: 2,
- width: aimPart.offsetWidth,
- height: aimPart.offsetHeight,
- allowTaint: true, // 允许污染画布
- proxy: '/imgProxy'
- }).then((canvas) => {
- let imgUrl = canvas.toDataURL('image/png', 1);
-
- let downLoadLink = document.createElement('a');
- downLoadLink.innerText = '下载'
- downLoadLink.download = '铸剑山庄.png';
- downLoadLink.href = imgUrl;
- downLoadLink.className = "downLoadLink"
- downLoadLink.style.display = "none";
-
- // 下载图片
- aimPart.appendChild(downLoadLink)
- window.setTimeout(() => {
- document.querySelector('.downLoadLink').dispatchEvent(new MouseEvent('click'));
- aimPart.removeChild(document.querySelector('.downLoadLink'))
- },500)
-
- })
之后便可以下载目标节点(示例中aimPart)的相应截图了~

希望本文会对您有所帮助~ ^_^