使用 use-react-screenshot 创建的图像渲染不正确

Dav*_*mon 5 javascript screenshot reactjs

我用来use-react-screenshot拍摄特定 dom 元素的屏幕截图,但图像变得很奇怪,看起来它部分渲染了 dom 元素

这是运行takescreenshot函数后生成的图像

我正在使用示例代码create-react-app

import logo from "./logo.svg";
import "./App.css";
import { createRef } from "react";
import { useScreenshot, createFileName } from "use-react-screenshot";

function App() {
    const ref = createRef(null);
    const [image, takeScreenShot] = useScreenshot({
        type: "image/jpeg",
        quality: 1.0,
    });

    const download = (image, { name = "img", extension = "jpg" } = {}) => {
        const a = document.createElement("a");
        a.href = image;
        a.download = createFileName(extension, name);
        a.click();
    };

    const downloadScreenshot = () => takeScreenShot(ref.current).then(download);

    return (
        <div className="App">
            <header className="App-header">
                <button onClick={downloadScreenshot}>
                    Download screenshot
                </button>
                <img src={logo} className="App-logo" alt="logo" ref={ref} />
            </header>
        </div>
    );
}

export default App;
Run Code Online (Sandbox Code Playgroud)

一个可以玩的沙箱

我不确定它是否与 html2canvas 作为peerDependency相关。无论我把它放在ref哪里,都会发生同样的错误

Bad*_*ibo 6

github上有很多与 SVG 无法使用 html2canvas 正确下载相关的问题。我怀疑这些是问题所在。用户提供的解决方案/解决方法包括对内部代码的代码修改。这又很难再维持下去了。下载时 Firefox 也显示空白图像。

我最好的解决方案是使用替代库,例如html-to-image。几分钟之内,一切似乎都正常了。(甚至火狐)

import * as htmlToImage from "html-to-image";
...
  const takeScreenShot = async (node) => {
    const dataURI = await htmlToImage.toJpeg(node);
    return dataURI;
  };

  const download = (image, { name = "img", extension = "jpg" } = {}) => {
    const a = document.createElement("a");
    a.href = image;
    a.download = createFileName(extension, name);
    a.click();
  };

  const downloadScreenshot = () => takeScreenShot(ref.current).then(download);
...
Run Code Online (Sandbox Code Playgroud)

代码沙箱

现在这可能不是最好的解决方案,但它是目前最好的替代工作解决方案。