vue+html2canvas前端截图,上传给服务端以及本地下载

一.安装:

npm install --save html2canvas

 二.引用:

在使用的页面:

import html2canvas from "html2canvas"  

 三.使用:

给要截图的外层div加ref

张三

外层控制下载的按钮

下载图片

第一种:

下载到本地:

downImage() {
      html2canvas(this.$refs.imageDom, {
        useCORS: true,  //页面内使用了跨域的图片需要加useCORS: true,不然图片截图时会不存在
        width: 770
      }).then(canvas => {  //自己模拟一个a标签,实现点击截图之后下载到本地的效果
        let link = document.createElement("a");    
        link.href = canvas.toDataURL(); //下载链接
        this.filename = `${new Date().getTime()}${util.randomNum(
          1000,
          9999
        )}.jpg`;  //文件名称
        link.setAttribute("download", this.filename);
        link.style.display = "none"; //a标签隐藏
        document.body.appendChild(link);
        link.click();
      });
}

第二种:

上传到服务器:

 

saveImage() {
      html2canvas(this.$refs.imageDom, {
        //dpi: window.devicePixelRatio * 2,
        scale: window.devicePixelRatio*2,//可以增加图片的清晰度相当于UI的几倍图,想要几倍图乘以几
        useCORS: true // 如果截图的内容里有图片,可能会有跨域的情况,加上这个参数,解决文件跨域问题
      }).then(canvas => {
        let url = canvas.toDataURL("image/png", 1.0);
        this.filename = `${new Date().getTime()}${util.randomNum(
          1000,
          9999
        )}.jpg`;
        this.file_url = this.dataURLtoFile(url, this.filename); //将文件转换成file的格式,就可以使用file_url传递给服务端了
      });
 },

vue+html2canvas前端截图,上传给服务端以及本地下载_第1张图片

你可能感兴趣的:(vue,html2canvas)