npm i use-react-screenshot
App.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
import React, { useRef, useState } from 'react'; import { useScreenshot } from 'use-react-screenshot'; const App = () => { // Define the ref for the element you want to capture const captureRef = useRef(null); // Use the hook from use-react-screenshot const [image, takeScreenshot] = useScreenshot({ type: 'image/png', // Choose the format (png, jpeg) quality: 1.0, // Set quality (0 to 1) }); // Handle the image download const handleDownload = () => { const link = document.createElement('a'); link.href = image; link.download = 'screenshot.png'; // The name of the image file link.click(); }; return ( <div style={{ textAlign: 'center', padding: '20px' }}> <h1>Take a Screenshot</h1> {/* Section to be captured */} <div ref={captureRef} style={{ width: '80%', margin: '0 auto', padding: '20px', backgroundColor: '#f0f0f0', borderRadius: '8px', boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)', textAlign: 'center', }} > <h2>Capture This Section</h2> <p>This is an example of content that will be captured in the screenshot.</p> </div> {/* Button to capture screenshot */} <button onClick={() => takeScreenshot(captureRef.current)} style={{ padding: '10px 20px', backgroundColor: '#4CAF50', color: 'white', border: 'none', borderRadius: '5px', marginTop: '20px', cursor: 'pointer', }} > Capture Screenshot </button> {/* Show the captured image preview */} {image && ( <div> <h3>Preview:</h3> <img src={image} alt="Screenshot Preview" style={{ width: '80%', marginTop: '20px' }} /> </div> )} {/* Button to download the captured screenshot */} {image && ( <button onClick={handleDownload} style={{ padding: '10px 20px', backgroundColor: '#2196F3', color: 'white', border: 'none', borderRadius: '5px', marginTop: '20px', cursor: 'pointer', }} > Download Screenshot </button> )} </div> ); }; export default App; |