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
✂️ Generates an image from a DOM node using HTML5 canvas and SVG.
npm install html-to-image
Typescript
Module System
Node Version
NPM Version
88.5
Supply Chain
100
Quality
76.2
Maintenance
100
Vulnerability
100
License
TypeScript (80.89%)
CSS (7.95%)
HTML (7.05%)
JavaScript (3.9%)
Shell (0.21%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
5,915 Stars
413 Commits
561 Forks
31 Watching
4 Branches
39 Contributors
Minified
Minified + Gzipped
Latest Version
1.11.11
Package Id
html-to-image@1.11.11
Unpacked Size
292.34 kB
Size
66.12 kB
File Count
82
NPM Version
8.11.0
Node Version
16.16.0
Publised On
01 Feb 2023
Cumulative downloads
Total Downloads
Last day
0%
0
Compared to previous day
Last week
0%
0
Compared to previous week
Last month
0%
0
Compared to previous month
Last year
0%
0
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:
1var node = document.getElementById('my-node'); 2 3htmlToImage.toPng(node) 4 .then(function (dataUrl) { 5 var img = new Image(); 6 img.src = dataUrl; 7 document.body.appendChild(img); 8 }) 9 .catch(function (error) { 10 console.error('oops, something went wrong!', error); 11 });
Get a PNG image base64-encoded data URL and download it (using download):
1htmlToImage.toPng(document.getElementById('my-node')) 2 .then(function (dataUrl) { 3 download(dataUrl, 'my-node.png'); 4 });
Get an SVG data URL, but filter out all the <i>
elements:
1function filter (node) { 2 return (node.tagName !== 'i'); 3} 4 5htmlToImage.toSvg(document.getElementById('my-node'), { filter: filter }) 6 .then(function (dataUrl) { 7 /* do something */ 8 });
Save and download a compressed JPEG image:
1htmlToImage.toJpeg(document.getElementById('my-node'), { quality: 0.95 }) 2 .then(function (dataUrl) { 3 var link = document.createElement('a'); 4 link.download = 'my-image-name.jpeg'; 5 link.href = dataUrl; 6 link.click(); 7 });
Get a PNG image blob and download it (using FileSaver):
1htmlToImage.toBlob(document.getElementById('my-node'))
2 .then(function (blob) {
3 if (window.saveAs) {
4 window.saveAs(blob, 'my-node.png');
5 } else {
6 FileSaver.saveAs(blob, 'my-node.png');
7 }
8 });
Get a HTMLCanvasElement, and display it right away:
1htmlToImage.toCanvas(document.getElementById('my-node'))
2 .then(function (canvas) {
3 document.body.appendChild(canvas);
4 });
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.toPixelData(node) 4 .then(function (pixels) { 5 for (var y = 0; y < node.scrollHeight; ++y) { 6 for (var x = 0; x < node.scrollWidth; ++x) { 7 pixelAtXYOffset = (4 * y * node.scrollHeight) + (4 * x); 8 /* pixelAtXY is a Uint8Array[4] containing RGBA values of the pixel at (x, y) in the range 0..255 */ 9 pixelAtXY = pixels.slice(pixelAtXYOffset, pixelAtXYOffset + 4); 10 } 11 } 12 });
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
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
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
SAST tool detected but not run on all commits
Details
Reason
Found 1/30 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
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
26 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-12-16
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