npm install html2canvas @1.0.0
注意:我项目中安装的html2canvas版本是1.0.0,可根据需要安装,如需安装最新版本,使用
npm install html2canvas -s
2. 引入依赖
import html2canvas from "html2canvas";
<div class="assets-left">
<div id="exportAll">
// 此处是导出的内容
</div>
</div>
<div @click="exportAction">报表导出</div>
// 导出 -> 这个是按钮的导出按钮的触发事件
const exportAction = () =>{
download();
}
// 下载
const download = () => {
let targetDom = document.getElementById("exportAll"); //原本需要截图的div
console.log(" ~ file: index.vue:33 ~ download ~ targetDom:", targetDom.clientWidth)
let clonedNode = targetDom.cloneNode(true); //复制一个
clonedNode.setAttribute(
"style",
`width: ${targetDom.clientHeight};height: ${targetDom.clientWidth};`
);
document.body.appendChild(clonedNode); //放到body后面
// 转换成canvas
html2canvas(targetDom, {
allowTaint: true,
taintTest: false,
}).then(function (canvas) {
var pageData = canvas.toDataURL("image/png", 1.0);
saveFile(
pageData.replace("image/png", "image/octet-stream"),
new Date().getTime() + ".png"
);
document.body.removeChild(clonedNode);
});
};
// 保存路径下载
function saveFile(data, filename) {
var save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
save_link.href = data;
save_link.download = filename;
document.body.appendChild(save_link);
save_link.click();
save_link.remove();
}
以上三个步骤就可以实现div指定区域内的图片,下一章具体讲解当内容区域很长,怎么导出滑块区域内的完整内容