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 = url
a.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>