引用方式
nstall NPM
npm install --save html2canvas
Install Yarn
yarn add html2canvas
Script src
http://html2canvas.hertzen.com/dist/html2canvas.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="./html2canvas.js"></script>
</head>
<body>
<div id="view" style="border:1px solid red;">
<img src="./pl-user.png" alt="">
<input type="button" value="截图" onclick="takeScreenshot()">
</div>
</body>
<script type="text/javascript">
function takeScreenshot() {
/*domId 配置参数 */
html2canvas(document.getElementById('view'), {
backgroundColor: "#fff",
useCORS: true // 如果截图的内容里有图片,可能会有跨域的情况,加上这个参数,解决文件跨域问题
// width: 300,
// height: 300
}).then((canvas) => {
//把截的图显示在网页上
document.body.appendChild(canvas);
//点击截图下载到本地
let url = canvas.toDataURL("image/png");
let a = document.createElement("a");
a.href = url;
a.download = "二维码";
a.click();
});
}
</script>
</html>
截图上传到服务器
html2canvas(document.getElementById('view'), {
backgroundColor: "#fff",
// width: 300,
// height: 300
}).then((canvas) => {
let base64 = canvas.toDataURL("image/png"); // 先转化为base64
/* 将html2canvas生成截图上传到服务器 */
let bstr = atob(base64.split(',')[1]); // atob是将base64编码解码,去掉data:image/png;base64,部分
let n = bstr.length;
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
let file2 = new File([u8arr], 'a.jpg', {type: 'image/jpg'})
var formData = new FormData();
formData.append("file", file2);
});