Skip to content

Instantly share code, notes, and snippets.

@kentcdodds
Created August 14, 2024 22:05
Show Gist options
  • Save kentcdodds/96c38d98cd1c5dfc9c3552884d8471b2 to your computer and use it in GitHub Desktop.
Save kentcdodds/96c38d98cd1c5dfc9c3552884d8471b2 to your computer and use it in GitHub Desktop.
Create a screenshot of a DOM element (while preserving a transparent background).
const { default: html2canvas } = await import(
'https://unpkg.com/html2canvas@1.4.1/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