安装
npm install --save html2canvas
1、简单实例
点击按钮截取id=capture 的元素
<template> <div id="capture" style="padding: 10px; background: #f5da55"> <h4 style="color: #000; ">Hello world!</h4> <button @click="screenshots">screenshots</button> </div> </template> <script> import html2canvas from "html2canvas"; export default { methods: { screenshots() { html2canvas(document.querySelector("#capture")).then(canvas => { document.body.appendChild(canvas); }); } } }; </script>
生成的图片可以右键保存
2、问题:截图不全
如果在vue项目中出现问题:截图不全,
可以通过生成虚拟dom的方法解决
代码如下
<template> <div id="capture" ref="imageDom" style="padding: 10px; background: #f5da55;height:1000px;width100%" > <h4 style="color: #000;">Hello world!</h4> <button @click="screenshots">screenshots</button> </div> </template> <script> import html2canvas from "html2canvas"; export default { methods: { screenshots() { let imageDom = this.$refs.imageDom; var width = imageDom.style.width; var cloneDom = imageDom.cloneNode(true); // 设置参数 cloneDom.style.padding = "16px"; cloneDom.style.position = "absolute"; cloneDom.style.top = "0px"; cloneDom.style.zIndex = "-1"; cloneDom.style.width = width; document.body.appendChild(cloneDom); html2canvas(cloneDom).then(canvas => { // 转成图片,生成图片地址 var imgUrl = canvas.toDataURL("image/png"); var eleLink = document.createElement("a"); eleLink.href = imgUrl; // 转换后的图片地址 eleLink.download = "pictureName"; // 触发点击 document.body.appendChild(eleLink); eleLink.click(); // 然后移除 document.body.removeChild(eleLink); }); cloneDom.style.display = "none"; } } }; </script>
3、截图并上传
安装axios
npm install --save axios
实现步骤:
1、点击按钮,通过html2canvas 将id为head-image 的元素截取为canvas
2、通过canvas 得到dataURL
3、将dataURL 转换为Blob二进制流
4、通过axios上传文件
<template> <div> <h4 style="color: red;" id="head-image">Hello world!</h4> <button @click="saveImage">screenshots</button> </div> </template> <script> import html2canvas from "html2canvas"; import axios from "axios"; export default { methods: { async saveImage() { const res = await this.html2canvasAndUploadFile("#head-image"); console.log(res); }, // 传入元素id,获取服务器返回的结果 async html2canvasAndUploadFile(selector) { const canvas = await html2canvas(document.querySelector(selector)); // 将canvas转成base64 let dataURL = canvas.toDataURL("image/png"); // 打印的是图片的base64编码 let blob = this.dataUrlToBlob(dataURL); return await this.uploadFile(blob); }, // 将base64转成图片文件流 dataUrlToBlob(dataUrl) { let arr = dataUrl.split(","), mime = arr[0].match(/:(.*?);/)[1], // arr[0]是data:image/png;base64 bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } let imgFile = new Blob([u8arr], { type: mime }); return imgFile; }, // 上传二进制文件 async uploadFile(blob) { const formData = new FormData(); formData.append("image", blob); const res = await axios({ method: "post", url: "/uploadurl", data: formData, headers: { "Content-Type": "multipart/form-data" } }); return res.data; } } }; </script>