Created
August 14, 2024 22:05
-
-
Save kentcdodds/96c38d98cd1c5dfc9c3552884d8471b2 to your computer and use it in GitHub Desktop.
Create a screenshot of a DOM element (while preserving a transparent background).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { default: html2canvas } = await import( | |
'https://unpkg.com/[email protected]/dist/html2canvas.esm.js' | |
) | |
async function captureElement(element, { scale = 1, backgroundColor = null } = {}) { | |
const canvas = await html2canvas(element, { | |
backgroundColor, | |
scale, | |
}) | |
// Convert the canvas to a PNG image with a transparent background | |
const pngImage = canvas.toDataURL('image/png') | |
// Create a link to download the image | |
const link = document.createElement('a') | |
link.href = pngImage | |
const timestamp = new Date() | |
.toISOString() | |
.replace(/:/g, '-') | |
.replace(/\./g, '-') | |
link.download = `screenshot-${timestamp}.png` | |
link.click() | |
} | |
// Example usage with 2x magnification and a specific background color: | |
// await captureElement(document.querySelector('#your-element-id'), { scale: 2, backgroundColor: '#ffffff' }) | |
// Or omit the scale and background for a scale of 1 and a transparent background |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment