安装html2canvas:
npm install --save html2canvas
注意:如果是某些原因不能npm的话就直接把依赖包拷贝到node_modules就可以啦
html:
<div class="details-box" v-show="detailsFormShow"><div class="details-inner"><!-- 截图区域 --><div ref="cutImageBox">…………</div><!-- 按钮部分 --><div class="btns"><el-buttontype="primary"@click="saveImage"size="small"style="margin-right: 30px">保存为图片</el-button><el-button type="primary" @click="detailsFormShow = false" size="small">关闭</el-button></div></div></div>
script:
引入html2canvas
import html2Canvas from "html2canvas";
methods:
重点:这个方法除了ie浏览器基本都支持,但在ie是不能用的
//保存图片这个方法除了ie浏览器基本都支持saveImage() {// 第一个参数是需要生成截图的元素,第二个是自己需要配置的参数,宽高等html2canvas(this.$refs.creditQrCodeShare, {backgroundColor: null, //画出来的图片有白色的边框,不要可设置背景为透明色(null)useCORS: true, //支持图片跨域scale: 1, //设置放大的倍数}).then((canvas) => {// 把生成的base64位图片上传到服务器,生成在线图片地址let url = canvas.toDataURL("image/png"); // toDataURL: 图片格式转成 base64this.imgUrl = url;//将图片下载到本地console.log(url,67)let a = document.createElement("a"); // 生成一个a元素let event = new MouseEvent("click"); // 创建一个单击事件a.download = name || "截图名称"; // 设置图片名称没有设置则为默认a.href = this.imgUrl; // 将生成的URL设置为a.href属性a.dispatchEvent(event); // 触发a的单击事件});},
在网上查了好多资料好多是说用这个方法IE浏览器可以用,但我试了是不行的:
if (userAgent.includes("Trident")) {let arr = image.split(',');let mime = arr[0].match(/:(.*?);/)[1];let bstr = atob(arr[1]);let n = bstr.length;let u8arr = new Uint8Array(n);while (n--) {u8arr[n] = bstr.charCodeAt(n);}window.navigator.msSaveBlob(new Blob([u8arr], {type: mime}), `${value}.jpg`);}
重点:想要在ie浏览器上用这个html2canvas来将html保存为图片并且在本地保存就要让后端来配合让其转为文件流来下载保存。可能写的有点儿乱,但如果是发现IE浏览器不能下载图片就跟后端商量用这个方式,其他的方法我都试过了都没用
1.//让后端写一个接口,你给它传`this.imgUrl` 转为base64位的参数。const htrs = window.location.hostconst pste = window.location.protocolconst newRowder = `${pste}//${htrs}${baseURL}/ieriepf/sdfjjfbase64`let aLink = document.createElement("a");aLink.href = downloadUrl;aLink.download = `${downloadName}.jpg`;document.body.appendChild(aLink);aLink.click();document.body.removeChild(aLink);