Reactjs 使用html2canvas将html区域导出为图像
我有一个React应用程序。我需要能够将组件导出为png/jpg。我正试图用html2canvas库实现这一点 我尝试过这种天真的方法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()
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>
);
}