实现功能:实现页面部分内容截图并且自动下载
html2canvas 传送门:http://html2canvas.hertzen.com/
实现思路:
- 准备一个放置截图后内容的div;
- 将html转化成canvas ,html2canvas()方法,是插件提供的,它的作用是把这个参数canvas形成一个img图片元素;
- 生成图片的地址 dataImg.src = canvas.toDataURL('image/png');
- 利用a标签的download属性实现下载
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
padding: 100px;
}
#admin{
width: 300px;
height: 1300px;
background: rebeccapurple;
color: black;
text-align: center;
line-height: 300px;
font-size: 30px;
}
.header{
width: 300px;
height: 400px;
background: #5a90a0;
font-size: 30px;
}
</style>
</head>
<body>
<div class="header">
我是占位头部
</div>
<div id="admin">
测试测试测试多晒晒
</div>
<button id="btn">截屏</button>
<div id="view"></div>
</body>
<script src="./html2canvas.js"></script>
<script>
let btn = document.querySelector('#btn')
btn.addEventListener('click',screenshot)
function screenshot() {
const targetDom = document.querySelector("#admin")
const copyDom = targetDom.cloneNode(true)
copyDom.style.width = targetDom.scrollWidth + 'px'
copyDom.style.height = targetDom.scrollHeight + 'px'
document.body.appendChild(copyDom)
var scrollY = targetDom.scrollTop;
var scrollX = targetDom.scrollLeft;
// 插入之前canvas下
html2canvas(document.querySelector("#admin"), {
allowTaint: false,
useCORS: true,
height: targetDom.scrollHeight,
width: targetDom.scrollWidth,
y:scrollY + targetDom.offsetTop ,
x:scrollX + targetDom.offsetLeft
}).then(canvas => {
copyDom.parentNode.removeChild(copyDom)
canvas.style.width = canvas.style.width + 'px'
canvas.style.height = canvas.style.height + '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')
const alink = document.createElement("a");
alink.href = dataImg.src;
alink.download = "testImg.jpg";
alink.click();
}, 0)
});
}
</script>
</html>
网友评论