【问题标题】:html2canvas giving blank imageshtml2canvas 给出空白图像
【发布时间】:2021-07-12 22:58:21
【问题描述】:

当我截屏时,我正在尝试使用 html2canvas 截屏我的 react 应用程序中的某些组件,但无论我尝试什么,图像总是变成空白。

这就是我的屏幕截图按钮的 onClick 侦听器中的代码。

            const help = document.querySelector("#help");
            html2canvas(help).then((canvas) => {
              console.log(help, canvas);
              const a = document.createElement("a");
              a.href = canvas.toDataURL("image/png");
              a.download = "help.png";
              a.click();
            });

这是#help 元素所包含的内容。

      <ul id="help">
        <li>Lorem</li>
        <li>lorem</li>
        <li>lorem</li>
        <li>lorem</li>
      </ul>

console.log 语句显示在 querySelector 中选择了正确的元素。我什至尝试根据我在此处的其他答案中看到的内容更改诸如 allowTaint、backgroundColor、foreignObjectRendering、useCORS 等字段,但这些似乎都不适合我。如果删除我所有的自定义 css 可能会有所帮助,但即使那样它也无法正常工作,也尝试过。将日志记录设置为 true 也没有给我任何输出,所以我几乎不知道从哪里开始。

【问题讨论】:

  • 在 React 中使用 querySelector 有点可疑。 React 是一个库,对于如何更新/渲染 DOM 有一个非常具体的工作流程。
  • 但我正在寻找的元素完全按照我的预期打印到控制台。而且#help 是在开始时呈现的,而我的屏幕截图按钮是稍后呈现的,所以我认为这与 querySelector 无法找到元素没有任何关系,除非我错过了一些东西。
  • @AdamJijo 你有没有找到任何解决方案,我在这里遇到同样的问题?

标签: javascript html css reactjs html2canvas


【解决方案1】:

尝试使用getElementById,它会起作用。

const getPrint = () => {
    const input = document.getElementById('headerr');
    html2canvas(input).then((canvas) => {
        document.body.appendChild(canvas);
        var imgWidth = 210;
        var pageHeight = 295;
        var imgHeight = (canvas.height * imgWidth) / canvas.width;
        var heightLeft = imgHeight;
        const imgData = canvas.toDataURL('image/png');
        //window.open(imgData);
        const pdf = new jsPDF('p', 'mm');
        var position = -2;
        pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;

        /* add extra pages if the div size is larger than a a4 size */
        while (heightLeft >= 0) {
            position = heightLeft - imgHeight;
            pdf.addPage();
            pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight);
            heightLeft -= pageHeight;
        }
        pdf.save('file.pdf');
    });
};

【讨论】:

  • 使用getElementByID 给了我同样的结果。另外,当我不尝试制作pdf时,我不明白您为什么在答案中使用jsPDF。
猜你喜欢
  • 2020-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-20
  • 2018-01-13
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多