Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 使用html2canvas将html区域导出为图像_Reactjs_Html2canvas - Fatal编程技术网

Reactjs 使用html2canvas将html区域导出为图像

Reactjs 使用html2canvas将html区域导出为图像,reactjs,html2canvas,Reactjs,Html2canvas,我有一个React应用程序。我需要能够将组件导出为png/jpg。我正试图用html2canvas库实现这一点 我尝试过这种天真的方法 const printDocument = () => { html2canvas(document.querySelector("#capture")).then(canvas => { document.body.appendChild(canvas); }); }; export default function App()

我有一个React应用程序。我需要能够将组件导出为png/jpg。我正试图用html2canvas库实现这一点

我尝试过这种天真的方法

const printDocument = () => {
  html2canvas(document.querySelector("#capture")).then(canvas => {
    document.body.appendChild(canvas);
  });
};

export default function App() {
  return (
    <div className="App">
      <div id="capture" style={{ padding: 10, background: "#f5da55" }}>
        <h4 style={{ color: "#000" }}>Hello world!</h4>
      </div>

      <button onClick={printDocument}>Print</button>
    </div>
  );
}

如何在ReactJs中实现这一点

使用以下导入语句

import html2canvas from 'html2canvas';
您可以使用react的钩子
useRef
hook

const printDocument = (domElement) => {
  html2canvas(domElement).then(canvas => {
    document.body.appendChild(canvas);
  });
};

export default function App() {

   const canvasRef = useRef()

  return (
    <div className="App">
      <div ref={canvasRef} style={{ padding: 10, background: "#f5da55" }}>
        <h4 style={{ color: "#000" }}>Hello world!</h4>
      </div>

      <button onClick={()=>printDocument(canvasRef.current)}>Print</button>
    </div>
  );
}
const printDocument=(doElement)=>{
html2canvas(domeElement)。然后(canvas=>{
document.body.appendChild(画布);
});
};
导出默认函数App(){
const canvasRef=useRef()
返回(
你好,世界!
printDocument(canvasRef.current)}>Print
);
}

您只需像这样更改html2canvas库的导入语句。

从“html2canvas”导入html2canvas


享受编码的乐趣。

你可以使用
Ref
来达到同样的目的,但是:(0,_html2canvas.html2canvas)不是function@Nemus您如何导入html2canvas?我使用了
从“html2canvas”导入html2canvas并且它正在工作。是的,这就是问题所在。我用{html2canvas}导入了它
const printDocument = (domElement) => {
  html2canvas(domElement).then(canvas => {
    document.body.appendChild(canvas);
  });
};

export default function App() {

   const canvasRef = useRef()

  return (
    <div className="App">
      <div ref={canvasRef} style={{ padding: 10, background: "#f5da55" }}>
        <h4 style={{ color: "#000" }}>Hello world!</h4>
      </div>

      <button onClick={()=>printDocument(canvasRef.current)}>Print</button>
    </div>
  );
}