js中实现页面截图(以vue为例)

js中截图操作原理为获取页面dom节点,在canvas画布里去绘制,然后通过canvas的todataurl方法转成base64编码格式,因为不是真正意义上的截图,所以一般存在部分css样式失效,图片加载失败的bug,谷歌上都能找到解决方案

在vue中使用

安装
npm install html2canvas --save
引入
 import html2canvas from 'html2canvas'
template
 <div id='nodeBox' class="content-body" slot="content">
                <div class="body-box">
                     <vue-qr 
                :text="downloadData.url" 
                :margin="0" 
                colorDark="#000" 
                colorLight="#fff" 
                :logoSrc="downloadData.icon" 
                :logoScale="0.3" 
                :size="200"></vue-qr>
                </div>
  </div>
scripts
//   截取图片
      setImage () {
      let that = this;
    //   event.preventDefault();
      var canvas2 = document.createElement("canvas");
      // let _canvas = document.getElementById('child');
      let _canvas = document.getElementById('nodeBox');
      var w = parseInt(window.getComputedStyle(_canvas).width);
      var h = parseInt(window.getComputedStyle(_canvas).height);
      //将canvas画布放大若干倍,然后盛放在较小的容器内,就显得不模糊了  
      canvas2.width = w * 4;
      canvas2.height = h * 4;
      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('child'), {
         html2canvas(document.getElementById('nodeBox'), {
        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)
      });
    },
    getBlob (canvas) { //获取blob对象
      var data = canvas.toDataURL("image/jpeg", 1);
      this.dataurl=data
      console.log(this.dataurl)
      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"
      });
    },
使用

因为是base64编码格式的图片,在使用时可以直接使img标签的src等于该图片编码就行,就是上文中的dataurl(在return中定义的变量)

 <img id='downImg' :src="dataurl" alt="">

你可能感兴趣的:(node.js,javascript,vue)