【问题标题】:html2canvas cors error while fetching images from external domain从外部域获取图像时出现 html2canvas cors 错误
【发布时间】:2023-02-11 12:46:54
【问题描述】:

我正在尝试将 React 组件导出为 PDF 我采取的步骤是

  • 使用 html2canvas 将组件转换为图像
  • 正在创建一个 pdf
  • 将图像附加到 pdf

该组件有一些图像,我通过调用它们的 API 获得其 URL,图像的 src 是外部域 url html2canvas 为外部域图像抛出 cors 错误

下面是html中的img元素

这是转换的代码块

html2canvas(containerDiv, { allowTaint: false, useCORS: true, logging: true, }) .then(function (canvas) { const imgData = canvas.toDataURL("image/png"); pdf.addImage(imgData, "PNG", 0, 0, width, height); pdf.save(${companyName}.pdf); }) .catch((err) => console.log(err));

已经尝试过的方法:

  1. 将 crossorigin 设置为 true 或 anonymous
  2. url的base64转换并添加到图片src
  3. 将随机查询字符串添加到图像 src
  4. 在 hmtl2canvas 选项中 AllowTaint 为真(不工作)

    如果有任何快速解决方法是可能的

【问题讨论】:

    标签: javascript html reactjs jspdf html2canvas


    【解决方案1】:

    我建议切换到modern-screenshot,它更轻巧并提供更好的输出质量,尤其是不需要设置代理服务器 - reference。否则,如果您更喜欢坚持使用 html2canvas 解决方案,则需要设置一个代理服务器(这里是 lib 作者本人的 example),获取服务器的 URL 并将其用作:

    html2canvas(element, {
      allowTaint: true,
      useCORS: true,
      proxy: <server_url>
    }).then(canvas => { ... });
    

    希望这可以帮助。

    【讨论】:

      猜你喜欢
      • 2018-06-09
      • 2021-04-21
      • 2018-04-01
      • 1970-01-01
      • 2014-11-07
      • 2015-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多