html-to-image

repository·master·Indexed 27 days ago

https://github.com/bubkoo/html-to-image

A library that generates images (PNG, JPEG, SVG, etc.) from DOM nodes using HTML5 canvas and SVG <foreignObject>. Version 1.11.13 provides functions such as toPng, toJpeg, toSvg, toBlob, toCanvas, and toPixelData to convert HTMLElements into various formats, including base64-encoded data URLs and raw RGBA pixel data.

Tokens
2.5K
Snippets
10
Records
20
Agent score
43%

What's inside html-to-image

  1. Import html-to-image

    master

    You can import the library using ES6 modules or CommonJS (ES5).

    /* ES6 */
    import * as htmlToImage from 'html-to-image';
    import { toPng, toJpeg, toBlob, toPixelData, toSvg } from 'html-to-image';
    
    /* ES5 */
    var htmlToImage = require('html-to-image');
  2. Configure html-to-image options

    master

    The following options can be passed to the rendering functions to customize the output:

    • filter: (domNode: HTMLElement) => boolean. Returns true to include the node. Excluding a node also excludes its children. Not called on the root node.
    • backgroundColor: A valid CSS color string.
    • width, height: Width and height in pixels applied to the node before rendering.
    • canvasWidth, canvasHeight: Scales the canvas size (including elements inside) to the specified dimensions.
    • style: An object of CSS properties to be applied to the node before rendering.
    • quality: A number between 0 and 1 for JPEG quality (default 1.0).
    • cacheBust: If true, appends current time as a query string to URL requests (default false).
    • includeQueryParams: If false, excludes query params from URLs used as cache keys (default false).
    • imagePlaceholder: A data URL for a placeholder image used if an image fetch fails.
    • pixelRatio: The pixel ratio of the captured image (default uses device ratio; set to 1 for initial-scale 1).
    • preferredFontFormat: Specifies the required font format (e.g., woff2) to optimize embedding.
    • fontEmbedCSS: A string of CSS used to skip the library's internal font parsing/embedding process. Useful when combined with getFontEmbedCSS().
    • skipAutoScale: If true, skips scaling extra-large DOMs into the canvas (may result in image clipping).
    • type: The image format (default image/png). Used by toCanvas to return a matching blob.
    • includeStyleProperties: An array of style property names to manually include when cloning nodes.
  3. Browser support and limitations

    master

    Requirements

    • Promise support.
    • SVG <foreignObject> tag support.
    • Note: Internet Explorer is not supported because it lacks <foreignObject> support.

    Known Issues

    • Tainted Canvas: If the DOM includes a <canvas> that is tainted (due to CORS), rendering will fail.
    • Data URI Limits: Rendering very large DOM trees may fail due to browser-specific limits on Data URI sizes.
  4. Use toSvg with a filter

    master

    Use toSvg to get an SVG data URL. You can provide a filter function in the options to exclude specific elements from the output.

    function filter (node) {
      return (node.tagName !== 'i');
    }
    
    htmlToImage
      .toSvg(document.getElementById('my-node'), { filter: filter })
      .then(function (dataUrl) {
        /* do something */
      });
  5. Use toPng to generate a PNG image

    master

    Use toPng to get a PNG image as a base64-encoded data URL. This is useful for displaying the image in an <img> tag or downloading it.

    const node = document.getElementById('my-node');
    
    htmlToImage
      .toPng(node)
      .then((dataUrl) => {
        const img = new Image();
        img.src = dataUrl;
        document.body.appendChild(img);
      })
      .catch((err) => {
        console.error('oops, something went wrong!', err);
      });
  6. Use html-to-image in React

    master

    To use html-to-image in a React component, use a useRef hook to reference the DOM node you want to capture.

    import React, { useCallback, useRef } from 'react';
    import { toPng } from 'html-to-image';
    
    const App: React.FC = () => {
      const ref = useRef<HTMLDivElement>(null)
    
      const onButtonClick = useCallback(() => {
        if (ref.current === null) {
          return
        }
    
        toPng(ref.current, { cacheBust: true, })
          .then((dataUrl) => {
            const link = document.createElement('a')
            link.download = 'my-image-name.png'
            link.href = dataUrl
            link.click()
          })
          .catch((err) => {
            console.log(err)
          })
      }, [ref])
    
      return (
        <>
          <div ref={ref}>
          {/* DOM nodes you want to convert to PNG */}
          </div>
          <button onClick={onButtonClick}>Click me</button>
        </>
      )
    }
  7. Use toJpeg with quality settings

    master

    Use toJpeg to save a compressed JPEG image. The quality option accepts a number between 0 and 1.

    htmlToImage
      .toJpeg(document.getElementById('my-node'), { quality: 0.95 })
      .then(function (dataUrl) {
        var link = document.createElement('a');
        link.download = 'my-image-name.jpeg';
        link.href = dataUrl;
        link.click();
      });
  8. Use toPixelData to get raw RGBA pixels

    master

    Use toPixelData to get the raw pixel data as a Uint8Array. Every 4 array elements represent the RGBA data of a single pixel.

    var node = document.getElementById('my-node');
    
    htmlToImage
      .toPixelData(node)
      .then(function (pixels) {
        for (var y = 0; y < node.scrollHeight; ++y) {
          for (var x = 0; x < node.scrollWidth; ++x) {
            pixelAtXYOffset = (4 * y * node.scrollHeight) + (4 * x);
            /* pixelAtXY is a Uint8Array[4] containing RGBA values of the pixel at (x, y) in the range 0..255 */
            pixelAtXY = pixels.slice(pixelAtXYOffset, pixelAtXYOffset + 4);
          }
        }
      });
  9. Use toBlob to get an image Blob

    master

    Use toBlob to get a PNG image blob, which can be used with libraries like FileSaver.js to trigger a download.

    htmlToImage
      .toBlob(document.getElementById('my-node'))
      .then(function (blob) {
        if (window.saveAs) {
          window.saveAs(blob, 'my-node.png');
        } else {
         FileSaver.saveAs(blob, 'my-node.png');
       }
      });
  10. Optimize font embedding with getFontEmbedCSS

    master

    To avoid redundant font parsing and embedding across multiple calls, use getFontEmbedCSS() to extract the CSS once, then pass it to subsequent calls via the fontEmbedCSS option.

    const fontEmbedCSS = await htmlToImage.getFontEmbedCSS(element1);
    html2Image.toSVG(element1, { fontEmbedCSS });
    html2Image.toSVG(element2, { fontEmbedCSS });