vue 使用html2canvas将div转化为图片

1. 安装

npm install html2canvas --save

引入

在当前页面引入该组件直接使用

import html2canvas from 'html2canvas'

2. 使用

<div id="newImg"> 你需要的转化成图片的内容</div>
	setImage () {
      let that = this;
      event.preventDefault();
      var canvas2 = document.createElement("canvas");
      let _canvas = document.getElementById('newImg');
      var w = parseInt(window.getComputedStyle(_canvas).width);
      var h = parseInt(window.getComputedStyle(_canvas).height);
      //将canvas画布放大若干倍,然后盛放在较小的容器内,就显得不模糊了  
      canvas2.width = w * 2;
      canvas2.height = h * 2;
      canvas2.style.width = w + "px";
      canvas2.style.height = h + "px";
      //可以按照自己的需求,对context的参数修改,translate指的是偏移量  
      //  var context = canvas.getContext("2d");  
      //  context.translate(0,0);  
      var context = canvas2.getContext("2d");
      context.scale(2, 2);
      html2canvas(document.getElementById('newImg'), {
        canvas: canvas2
      }).then(function (canvas) {
        var blob = that.getBlob(canvas);
        var oMyForm = new FormData();
        var fileName = "mobile" + '.jpg'
        oMyForm.append("file", blob, fileName);
        //				oMyForm.append("fileName", fileName);    
        oMyForm.append("fileType", 'image');
        oMyForm.append("user_id", that.global.company.id)
        that.uploadFile(that.global.ossservice + "/oss/uploadorgFile", oMyForm).then(res => {
          if (res.data.errorCode != '00') {
            that.$message.error(res.data.errorMsg);
            return;
          }
          return res.data.sprbody.urlAddress;
        });

      });
    },
    getBlob (canvas) { //获取blob对象
      var data = canvas.toDataURL("image/jpeg", 1);
      data = data.split(',')[1];
      data = window.atob(data);
      var ia = new Uint8Array(data.length);
      for (var i = 0; i < data.length; i++) {
        ia[i] = data.charCodeAt(i);
      }
      return new Blob([ia], {
        type: "image/jpeg"
      });
    },

你可能感兴趣的:(vue 使用html2canvas将div转化为图片)