使用 canvas 实现页面截图

16 阅读1分钟
实现
import html2canvas from 'html2canvas';

// 保存图片
const downloadImage = (filename = 'snapshoot', imageUrl = null) => {
  if (!imageUrl) {
    throw '缺少图片地址!';
  }

  const DA = document.createElement('a'); // 新建一个 a 标签
  DA.download = (filename || 'snapshoot') + '.png';
  DA.href = imageUrl;
  document.body.appendChild(DA);
  DA.click();
  DA.remove();
};

// 页面截图
const Snapshoot = (element, filename = 'snapshoot') => {
  if (!element) {
    throw '缺少元素!';
  }

  const canvas = document.createElement('canvas'); // 创建 canvas 标签
  const width = parseInt(window.getComputedStyle(element).width); // 获取元素宽
  const height = parseInt(window.getComputedStyle(element).height); // 获取元素高

  // 以下 "? * 4" 均为解决截图不完整问题,不可缺少

  canvas.width = width * 4;
  canvas.height = height * 4;

  const options = {
    canvas,
    useCORS: true, // 尝试使用 CORS 从服务器加载图像,解决跨域问题
    allowTaint: true, // 图片跨域相关属性
    tainttest: true, // 是否在渲染前测试图片
    logging: false, // 不启动日志调试
    scrollX: 0, // 水平偏移量
    scrollY: 0, // 垂直偏移量
    scale: 4, // 按比例增加分辨率
    dpi: window.devicePixelRatio * 4, // 设备像素
  };

  // 生成图片
  html2canvas(element, options).then((canvas) => {
    const dataURL = canvas.toDataURL('image/png');
    downloadImage(filename, dataURL);
  });
};

export default Snapshoot;

使用
const element = document.getElementById('snapshoot');
Snapshoot(element, '截图');