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



我有一个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中实现这一点?

使用以下导入语句

import html2canvas from 'html2canvas';

您可以使用react 的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>
);
}

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

import html2canvas from 'html2canvas';

享受编码。

最新更新