利用html2canvas 导出网页 (只是用于自己的笔记,如果需要看配置,自行查找插件api)

准备工作

  • 安装插件 npm install html2canvas -S

  • 原理其实就是利用 canvas 绘图,然后导出一个 base64 的字节流

  • a标签下载 图片有data URLs长度限制问题,这个url指的是base64的数据长度大小,限制各有不同,所以这里用canvas的blob方法将base64字节流转为二进制对象然后通过URL.createObjectURL(blob)生成一个指向blob对象的url,通过a标签的下载功能就可以下载了

  • 导处图片参考了知乎

  • 相关代码

import html2canvas from 'html2canvas';
let canvas; //这里的声明是为了导出图片的功能,让此变量可以多个函数作用域访问
// 生成图片
function createImg(){
         const imgDom = // 获取你的dom
          canvas = document.createElement("canvas")
          // 获取父级的宽高
          let body = document.querySelector('.home')
          const width = parseInt(window.getComputedStyle(body).width)
          const height = parseInt(window.getComputedStyle(body).height)
          // 定义放大倍数,可支持小数
          let scale = this.getPixelRatio()
          // 设定 canvas 元素属性宽高为 DOM 节点宽高 * 像素比
          canvas.width = width * scale
          canvas.height = height * scale
          // 设定 canvas css宽高为 DOM 节点宽高
          canvas.style.width = width + 'px';
          canvas.style.height = height + 'px';
          console.log(width, height);
          html2canvas(imgDom, { dpi: window.devicePixelRatio * 2, canvas: canvas, scale: scale, useCORS: true }).then((canvas) => {
            const context = canvas.getContext('2d');
            context.mozImageSmoothingEnabled = false;
            context.webkitImageSmoothingEnabled = false;
            context.msImageSmoothingEnabled = false;
            context.imageSmoothingEnabled = false;
            let dataURL = canvas.toDataURL("image/png")
            this.src = dataURL;
          });
}

// 导出图片
function downImg() {
        canvas.toBlob(function (blob) {
          let url = URL.createObjectURL(blob);
          var link = document.createElement('a');
          link.textContent = 'download image';
          link.href = url;
          link.download = "mypainting.jpeg";
          link.click()
          URL.revokeObjectURL(url);
        });
      }
posted @ 2021-04-25 16:10  阿臻  阅读(247)  评论(0编辑  收藏  举报