Gathering detailed insights and metrics for html-to-image
Gathering detailed insights and metrics for html-to-image
Gathering detailed insights and metrics for html-to-image
Gathering detailed insights and metrics for html-to-image
dom-to-image
Generates an image from a DOM node using HTML5 canvas and SVG
dom-to-image-more
Generates an image from a DOM node using HTML5 canvas and SVG
node-html-to-image
A Node.js library that generates images from HTML
blueimp-load-image
JavaScript Load Image is a library to load images provided as File or Blob objects or via URL. It returns an optionally scaled, cropped or rotated HTML img or canvas element. It also provides methods to parse image metadata to extract IPTC and Exif tags a
✂️ Generates an image from a DOM node using HTML5 canvas and SVG.
npm install html-to-image
Typescript
Module System
Node Version
NPM Version
98.8
Supply Chain
100
Quality
78
Maintenance
100
Vulnerability
100
License
TypeScript (82.58%)
CSS (7.22%)
HTML (6.46%)
JavaScript (3.55%)
Shell (0.19%)
Total Downloads
55,087,274
Last Day
134,393
Last Week
613,499
Last Month
3,015,529
Last Year
26,066,612
MIT License
6,266 Stars
452 Commits
591 Forks
30 Watchers
2 Branches
48 Contributors
Updated on Apr 24, 2025
Minified
Minified + Gzipped
Latest Version
1.11.13
Package Id
html-to-image@1.11.13
Unpacked Size
307.70 kB
Size
69.41 kB
File Count
82
NPM Version
10.8.2
Node Version
20.18.0
Published on
Feb 14, 2025
Cumulative downloads
Total Downloads
Last Day
-6.8%
134,393
Compared to previous day
Last Week
-18%
613,499
Compared to previous week
Last Month
4.4%
3,015,529
Compared to previous month
Last Year
75.6%
26,066,612
Compared to previous year
27
✂️ Generates an image from a DOM node using HTML5 canvas and SVG.
Fork from dom-to-image with more maintainable code and some new features.
1npm install --save html-to-image
1/* ES6 */ 2import * as htmlToImage from 'html-to-image'; 3import { toPng, toJpeg, toBlob, toPixelData, toSvg } from 'html-to-image'; 4 5/* ES5 */ 6var htmlToImage = require('html-to-image');
All the top level functions accept DOM node and rendering options, and return a promise fulfilled with corresponding dataURL:
Go with the following examples.
Get a PNG image base64-encoded data URL and display it right away:
1const node = document.getElementById('my-node'); 2 3htmlToImage 4 .toPng(node) 5 .then((dataUrl) => { 6 const img = new Image(); 7 img.src = dataUrl; 8 document.body.appendChild(img); 9 }) 10 .catch((err) => { 11 console.error('oops, something went wrong!', err); 12 });
Get a PNG image base64-encoded data URL and download it (using download):
1htmlToImage 2 .toPng(document.getElementById('my-node')) 3 .then((dataUrl) => download(dataUrl, 'my-node.png'));
Get an SVG data URL, but filter out all the <i>
elements:
1function filter (node) { 2 return (node.tagName !== 'i'); 3} 4 5htmlToImage 6 .toSvg(document.getElementById('my-node'), { filter: filter }) 7 .then(function (dataUrl) { 8 /* do something */ 9 });
Save and download a compressed JPEG image:
1htmlToImage 2 .toJpeg(document.getElementById('my-node'), { quality: 0.95 }) 3 .then(function (dataUrl) { 4 var link = document.createElement('a'); 5 link.download = 'my-image-name.jpeg'; 6 link.href = dataUrl; 7 link.click(); 8 });
Get a PNG image blob and download it (using FileSaver):
1htmlToImage
2 .toBlob(document.getElementById('my-node'))
3 .then(function (blob) {
4 if (window.saveAs) {
5 window.saveAs(blob, 'my-node.png');
6 } else {
7 FileSaver.saveAs(blob, 'my-node.png');
8 }
9 });
Get a HTMLCanvasElement, and display it right away:
1htmlToImage
2 .toCanvas(document.getElementById('my-node'))
3 .then(function (canvas) {
4 document.body.appendChild(canvas);
5 });
Get the raw pixel data as a Uint8Array with every 4 array elements representing the RGBA data of a pixel:
1var node = document.getElementById('my-node'); 2 3htmlToImage 4 .toPixelData(node) 5 .then(function (pixels) { 6 for (var y = 0; y < node.scrollHeight; ++y) { 7 for (var x = 0; x < node.scrollWidth; ++x) { 8 pixelAtXYOffset = (4 * y * node.scrollHeight) + (4 * x); 9 /* pixelAtXY is a Uint8Array[4] containing RGBA values of the pixel at (x, y) in the range 0..255 */ 10 pixelAtXY = pixels.slice(pixelAtXYOffset, pixelAtXYOffset + 4); 11 } 12 } 13 });
1import React, { useCallback, useRef } from 'react'; 2import { toPng } from 'html-to-image'; 3 4const App: React.FC = () => { 5 const ref = useRef<HTMLDivElement>(null) 6 7 const onButtonClick = useCallback(() => { 8 if (ref.current === null) { 9 return 10 } 11 12 toPng(ref.current, { cacheBust: true, }) 13 .then((dataUrl) => { 14 const link = document.createElement('a') 15 link.download = 'my-image-name.png' 16 link.href = dataUrl 17 link.click() 18 }) 19 .catch((err) => { 20 console.log(err) 21 }) 22 }, [ref]) 23 24 return ( 25 <> 26 <div ref={ref}> 27 {/* DOM nodes you want to convert to PNG */} 28 </div> 29 <button onClick={onButtonClick}>Click me</button> 30 </> 31 ) 32}
1(domNode: HTMLElement) => boolean
A function taking DOM node as argument. Should return true if passed node should be included in the output. Excluding node means excluding it's children as well.
You can add filter to every image function. For example,
1const filter = (node: HTMLElement) => { 2 const exclusionClasses = ['remove-me', 'secret-div']; 3 return !exclusionClasses.some((classname) => node.classList?.contains(classname)); 4} 5 6htmlToImage.toJpeg(node, { quality: 0.95, filter: filter});
or
1htmlToImage.toPng(node, {filter:filter})
Not called on the root node.
A string value for the background color, any valid CSS color value.
Width and height in pixels to be applied to node before rendering.
Allows to scale the canva's size including the elements inside to a given width and height (in pixels).
An object whose properties to be copied to node's style before rendering. You might want to check this reference for JavaScript names of CSS properties.
A number between 0
and 1
indicating image quality (e.g. 0.92
=> 92%
) of the JPEG image.
Defaults to 1.0
(100%
)
Set to true to append the current time as a query string to URL requests to enable cache busting.
Defaults to false
Set false to use all URL as cache key. If the value has falsy value, it will exclude query params from the provided URL.
Defaults to false
A data URL for a placeholder image that will be used when fetching an image fails.
Defaults to an empty string and will render empty areas for failed images.
The pixel ratio of the captured image. Default use the actual pixel ratio of the device. Set 1
to
use as initial-scale 1
for the image.
The format required for font embedding. This is a useful optimisation when a webfont provider specifies several different formats for fonts in the CSS, for example:
1@font-face { 2 name: 'proxima-nova'; 3 src: url("...") format("woff2"), url("...") format("woff"), url("...") format("opentype"); 4}
Instead of embedding each format, all formats other than the one specified will be discarded. If this option is not specified then all formats will be downloaded and embedded.
When supplied, the library will skip the process of parsing and embedding webfont URLs in CSS,
instead using this value. This is useful when combined with getFontEmbedCSS()
to only perform the
embedding process a single time across multiple calls to library functions.
1const fontEmbedCSS = await htmlToImage.getFontEmbedCSS(element1); 2html2Image.toSVG(element1, { fontEmbedCSS }); 3html2Image.toSVG(element2, { fontEmbedCSS });
When supplied, the library will skip the process of scaling extra large doms into the canvas object.
You may experience loss of parts of the image if set to true
and you are exporting a very large image.
Defaults to false
A string indicating the image format. The default type is image/png; that type is also used if the given type isn't supported. When supplied, the toCanvas function will return a blob matching the given image type and quality.
Defaults to image/png
An array of style property names. Can be used to manually specify which style properties are included when cloning nodes. This can be useful for performance-critical scenarios.
Only standard lib is currently used, but make sure your browser supports:
<foreignObject>
tagIt's tested on latest Chrome, Firefox and Safari (49, 45 and 16 respectively at the time of writing), with Chrome performing significantly better on big DOM trees, possibly due to it's more performant SVG support, and the fact that it supports CSSStyleDeclaration.cssText
property.
Internet Explorer is not (and will not be) supported, as it does not support SVG <foreignObject>
tag.
There might some day exist (or maybe already exists?) a simple and standard way of exporting parts of the HTML to image (and then this script can only serve as an evidence of all the hoops I had to jump through in order to get such obvious thing done) but I haven't found one so far.
This library uses a feature of SVG that allows having arbitrary HTML content inside of the <foreignObject>
tag. So, in order to render that DOM node for you, following steps are taken:
@font-face
declarations that might represent web fonts<style>
element, then attach it to the clone<img>
elementsbackground
CSS property, in a fashion similar to fonts<foreignObject>
tag, then into the SVG, then make it a data URL<canvas>
element with something drawn on it, it should be handled fine, unless the canvas is tainted - in this case rendering will rather not succeed.Please let us know how can we help. Do check out issues for bug reports or suggestions first.
To become a contributor, please follow our contributing guide.
The scripts and documentation in this project are released under the MIT License
No vulnerabilities found.
Reason
30 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 10
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
SAST tool detected but not run on all commits
Details
Reason
Found 7/29 approved changesets -- score normalized to 2
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
project is not fuzzed
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
security policy file not detected
Details
Reason
30 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-04-21
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More