使用 html2canvas 截取页面生成图片,报错 Tainted canvases may not be exported

因为截取的页面dom中,部分元素有引入cdn的图片

所以直接用 html2canvas 生成开始会报跨域的错,配置了 useCORS: true 也依旧报错

然后我找到的解决方法是,在 html2canvas 里配置 allowTaint: true

但是在调用 html2canvas 的回调方法 toDataURL 的时候又报错了,就是标题上的错误
Tainted canvases may not be exported

应该如何解决呢?

下面是相关的代码

const dom = document.querySelector('#poster')
const opt = {
    allowTaint: true, // Whether to allow cross-origin images to taint the canvas
    // useCORS: true, // 使用跨域(当allowTaint为true时这段代码没什么用)
    imageTimeout: 5000 // 设置图片的超时,设置0为禁用
  }

html2canvas(dom, opt).then(canvas => {
  const imageUrl = canvas.toDataURL('image/png') // 将canvas转成base64图片格式
  this.canvasImageUrl = imageUrl
  this.isDom = false
})
阅读 4k
1 个回答

让你们运维去 CDN 服务商那里配置 CORS。

跨域问题纯前端无法解决。

P.S. 你要先弄明白 allowTaint 是啥意思,它只能是把跨域的图片“画”在 canvas 上,但依旧不能 canvas.toXXX() 转换。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题