html2canvas截图

发布时间 2023-11-28 21:12:03作者: 随手笔记

注意:
1、supervision_box 获取的Dom节点一定不能使用 overflow:auto, 否则滚动的内容将无法截图(overflow:auto放在父级上面滚动)
2、height: 2800 一定要大于Dom的高度 否则也截图不完整

const downImg = () => {
  const box = document.querySelector('.supervision_box')
  html2canvas(box, {
    logging: false,
    allowTaint: true,
    scale: window.devicePixelRatio,
    width: box.offsetWidth, //dom 原始宽度
    height: 2800, // 截图的长度
    scrollY: 0,
    scrollX: 0,
    useCORS: true,
    backgroundColor: '#ffffff'
  }).then(function (canvas) {
    let imgUrl = canvas.toDataURL('image/png')
    var tempLink = document.createElement('a') // 创建一个a标签
    tempLink.style.display = 'none'
    tempLink.href = imgUrl
    tempLink.setAttribute('download', `生产监督.png`)
    if (typeof tempLink.download === 'undefined') {
      tempLink.setAttribute('target', '_blank')
    }
    document.body.appendChild(tempLink) // 将a标签添加到body当中
    tempLink.click() // 启动下载
    document.body.removeChild(tempLink) // 下载完毕删除a标签
    window.URL.revokeObjectURL(imgUrl)
  })
}