Convert any HTML DOM node into an image in PNG, JPEG, SVG, or Blob format.
Users request to convert HTML content to an image, take a screenshot of a web page element, generate a PNG/JPEG cover image, or export a specified DOM node as an image file.
Install html-to-image in the project directory:
bash
npm install html-to-image
Step 1: Target the DOM Node
Get the HTML element to convert using a selector:
js
const node = document.querySelector('#target-element');
Step 2: Choose Output Format
FormatFunctionDescriptionPNGtoPng(node, options)Default format, transparency preservedJPEGtoJpeg(node, { quality: 0.95 })Compressible, suitable for photosSVGtoSvg(node, { filter })Vector formatBlobtoBlob(node)Binary format, suitable for file downloads
Step 3: Trigger Download
js
htmlToImage.toPng(node, { cacheBust: true })
.then((dataUrl) => {
const link = document.createElement('a');
link.download = 'my-image.png';
link.href = dataUrl;
link.click();
})
.catch((err) => console.error('oops, something went wrong!', err));
OptionTypeDescriptionbackgroundColorstringCSS color value, e.g. '#ffffff'``width, heightnumberPixel dimensions to apply to the node before renderingcanvasWidth, canvasHeightnumberScaling dimensions for the canvasqualitynumberJPEG quality 0~1, default 1.0cacheBustbooleanAppend a timestamp to disable caching, default falsepixelRationumberPixel ratio; defaults to the device's actual pixel ratio; set to 1 to render at 1x initial scalefilterfunction(node) => boolean, returns true to keep the node
js
const filter = (node) => {
const exclude = ['remove-me', 'secret-div'];
return !exclude.some(c => node.classList?.contains(c));
};
htmlToImage.toJpeg(node, { quality: 0.95, filter });
tsx
import { useCallback, useRef } from 'react';
import { toPng } from 'html-to-image';
const ExportButton = () => {
const ref = useRef<HTMLDivElement>(null);
const onClick = useCallback(() => {
if (!ref.current) return;
toPng(ref.current, { cacheBust: true })
.then((dataUrl) => {
const link = document.createElement('a');
link.download = 'my-image.png';
link.href = dataUrl;
link.click();
})
.catch(console.error);
}, []);
return (
<>
<div ref={ref}>
{/* Content to convert */}
</div>
<button onClick={onClick}>Download Image</button>
</>
);
};
<canvas> will cause rendering to fail<foreignObject>)