将html区域导出为带有html2canvas的图像

问题描述 投票:0回答:1

我有一个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>
  );
}

但是我遇到一个错误:

TypeError
(0 , _html2canvas.html2canvas) is not a function
printDocument
/src/App.js:12:14
   9 | // };
  10 | 
  11 | const printDocument = () => {
> 12 |   html2canvas(document.querySelector("#capture")).then(canvas => {
     |              ^
  13 |     document.body.appendChild(canvas);
  14 |   });
  15 | };

我如何在ReactJs中实现这一目标?

reactjs html2canvas
1个回答
0
投票

使用以下导入语句

import html2canvas from 'html2canvas';

您可以使用useRef反应挂钩

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>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.