html-to-image

Generates an image from a DOM node using HTML5 canvas and SVG.

README

html-to-image

✂️ 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.

MIT LicenseLanguagePRs Welcome

buildcoverageLanguage grade: JavaScriptNPM PackageNPM Downloads


Install


  1. ``` sh
  2. npm install --save html-to-image
  3. ```

Usage


  1. ``` js
  2. /* ES6 */
  3. import * as htmlToImage from 'html-to-image';
  4. import { toPng, toJpeg, toBlob, toPixelData, toSvg } from 'html-to-image';

  5. /* ES5 */
  6. var htmlToImage = require('html-to-image');
  7. ```

All the top level functions accept DOM node and rendering options, and return a promise fulfilled with corresponding dataURL:


Go with the following examples.

toPng

Get a PNG image base64-encoded data URL and display it right away:

  1. ``` js
  2. var node = document.getElementById('my-node');

  3. htmlToImage.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.   });
  12. ```

Get a PNG image base64-encoded data URL and download it (using download):

  1. ``` js
  2. htmlToImage.toPng(document.getElementById('my-node'))
  3.   .then(function (dataUrl) {
  4.     download(dataUrl, 'my-node.png');
  5.   });
  6. ```

toSvg

Get an SVG data URL, but filter out all the `` elements:

  1. ``` js
  2. function filter (node) {
  3.   return (node.tagName !== 'i');
  4. }

  5. htmlToImage.toSvg(document.getElementById('my-node'), { filter: filter })
  6.   .then(function (dataUrl) {
  7.     /* do something */
  8.   });
  9. ```

toJpeg

Save and download a compressed JPEG image:

  1. ``` js
  2. htmlToImage.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.   });
  9. ```

toBlob

Get a PNG image blob and download it (using FileSaver):

  1. ``` js
  2. htmlToImage.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.   });
  10. ```

toCanvas

Get a HTMLCanvasElement, and display it right away:

  1. ``` js
  2. htmlToImage.toCanvas(document.getElementById('my-node'))
  3.   .then(function (canvas) {
  4.     document.body.appendChild(canvas);
  5.   });
  6. ```

toPixelData

Get the raw pixel data as a Uint8Array with every 4 array elements representing the RGBA data of a pixel:

  1. ``` js
  2. var node = document.getElementById('my-node');

  3. htmlToImage.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.   });
  13. ```

React

  1. ```tsx
  2. import React, { useCallback, useRef } from 'react';
  3. import { toPng } from 'html-to-image';

  4. const App: React.FC = () => {
  5.   const ref = useRef<HTMLDivElement>(null)

  6.   const onButtonClick = useCallback(() => {
  7.     if (ref.current === null) {
  8.       return
  9.     }

  10.     toPng(ref.current, { cacheBust: true, })
  11.       .then((dataUrl) => {
  12.         const link = document.createElement('a')
  13.         link.download = 'my-image-name.png'
  14.         link.href = dataUrl
  15.         link.click()
  16.       })
  17.       .catch((err) => {
  18.         console.log(err)
  19.       })
  20.   }, [ref])

  21.   return (
  22.     <>
  23.       <div ref={ref}>
  24.       {/* DOM nodes you want to convert to PNG */}
  25.       </div>
  26.       <button onClick={onButtonClick}>Click me</button>
  27.     </>
  28.   )
  29. }
  30. ```

Options


filter


  1. ```ts
  2. (domNode: HTMLElement) => boolean
  3. ```

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,

  1. ``` js
  2. const filter = (node)=>{
  3.   const exclusionClasses = ['remove-me', 'secret-div'];
  4.   return !exclusionClasses.some(classname=>node.classList.includes(classname));
  5. }

  6. htmlToImage.toJpeg(node, { quality: 0.95, filter: filter});
  7. ```
or

  1. ``` js
  2. htmlToImage.toPng(node, {filter:filter})
  3. ```

Not called on the root node.

backgroundColor


A string value for the background color, any valid CSS color value.

width, height


Width and height in pixels to be applied to node before rendering.

canvasWidth, canvasHeight


Allows to scale the canva's size including the elements inside to a given width and height (in pixels).

style


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.

quality


A number between 0 and 1 indicating image quality (e.g. 0.92 => 92%) of the JPEG image.

Defaults to 1.0 (100%)

cacheBust


Set to true to append the current time as a query string to URL requests to enable cache busting.

Defaults to false

includeQueryParams


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

imagePlaceholder


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.

pixelRatio


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.

preferredFontFormat


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. ```css
  2. @font-face {
  3.   name: 'proxima-nova';
  4.   src: url("...") format("woff2"), url("...") format("woff"), url("...") format("opentype");
  5. }
  6. ```

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.

fontEmbedCSS


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.

  1. ``` js
  2. const fontEmbedCss = await htmlToImage.getFontEmbedCSS(element1);
  3. html2Image.toSVG(element1, { fontEmbedCss });
  4. html2Image.toSVG(element2, { fontEmbedCss });
  5. ```

skipAutoScale


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  

type


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  

Browsers


Only standard lib is currently used, but make sure your browser supports:

- SVG `` tag

It's tested on latest Chrome and Firefox (49 and 45 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 `` tag.*

*Safari is not supported, as it uses a stricter security model on `` tag. Suggested workaround is to use `toSvg` and render on the server.*

How it works


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 `` tag. So, in order to render that DOM node for you, following steps are taken:

1. Clone the original DOM node recursively
2. Compute the style for the node and each sub-node and copy it to corresponding clone
   - and don't forget to recreate pseudo-elements, as they are not cloned in any way, of course
3. Embed web fonts
   - find all the @font-face declarations that might represent web fonts
   - parse file URLs, download corresponding files
   - base64-encode and inline content as dataURLs
- concatenate all the processed CSS rules and put them into one `