1.安装 html2canvas
npm install html2canvas
2.创建截图功能组件
import React, { useRef } from 'react';
import html2canvas from 'html2canvas';
const ScreenshotComponent = () => {
// 使用 useRef 创建一个引用,用于指向需要截图的元素
const captureRef = useRef(null);
// 定义截图按钮的点击事件处理函数
const handleCaptureClick = () => {
const element = captureRef.current; // 获取引用的元素
html2canvas(element) // 使用 html2canvas 将元素转换为 canvas
.then(canvas => {
const imgData = canvas.toDataURL('image/png'); // 将 canvas 转换为数据 URL
const link = document.createElement('a'); // 创建一个隐藏的链接元素
link.href = imgData; // 设置链接的 href 属性为数据 URL
link.download = 'screenshot.png'; // 设置下载文件名
link.click(); // 触发点击事件,下载截图
});
};
return (
<div>
{/* 包含需要截图内容的元素,并将其引用传递给 captureRef */}
<div ref={captureRef} style={{ padding: '10px', border: '1px solid #000' }}>
<h1>Hello, World!</h1>
<p>This content will be captured as an image.</p>
</div>
{/* 截图按钮 */}
<button onClick={handleCaptureClick}>Capture Screenshot</button>
</div>
);
};
export default ScreenshotComponent;
3.使用组件
import React from 'react';
import ReactDOM from 'react-dom/client';
import ScreenshotComponent from './ScreenshotComponent';
const App = () => {
return (
<div>
<h1>My React App</h1>
{/* 引入并使用截图组件 */}
<ScreenshotComponent />
</div>
);
};
// 获取 root DOM 节点,并在其中渲染 App 组件
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);