使用 html2canvas 将 html 区域导出为图像
Export html area as image with html2canvas
我有一个 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';
你可以使用useRef
react的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>
);
}
您只需像这样更改 html2canvas 库的导入语句。
import html2canvas from 'html2canvas';
享受编码。
我有一个 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';
你可以使用useRef
react的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>
);
}
您只需像这样更改 html2canvas 库的导入语句。
import html2canvas from 'html2canvas';
享受编码。