dom-to-image

repository·master·Indexed 27 days ago

https://github.com/tsayen/dom-to-image

A JavaScript library (version 2.6.0) that converts arbitrary DOM nodes into vector (SVG) or raster (PNG, JPEG) images. It works by cloning the node, embedding fonts and images as data URLs, and wrapping the result in an SVG <foreignObject>. It provides functions such as toPng, toJpeg, toBlob, toSvg, and toPixelData, with configurable options for filtering, background colors, and dimensions.

Tokens
3.1K
Snippets
5
Records
20
Agent score
90%

What's inside dom-to-image

  1. Install dom-to-image via NPM or Bower

    master

    NPM

    Install the package using npm:

    npm install dom-to-image

    Then import it in your project:

    /* ES 6 */
    import domtoimage from 'dom-to-image';
    
    /* ES 5 */
    var domtoimage = require('dom-to-image');

    Bower

    Install using bower:

    bower install dom-to-image

    Include src/dom-to-image.js or dist/dom-to-image.min.js in your HTML. This will make the domtoimage variable available in the global scope.

    import domtoimage from 'dom-to-image';
  2. Configure rendering options

    master

    When calling rendering functions, you can pass an options object with the following keys:

    OptionTypeDescription
    filterfunctionA function taking a DOM node. Return true to include the node (and its children) in the output. Not called on the root node.
    bgcolorstringAny valid CSS color value for the background.
    heightnumberHeight in pixels to be applied to the node before rendering.
    widthnumberWidth in pixels to be applied to the node before rendering.
    styleobjectProperties to be copied to the node's style before rendering (e.g., { fontSize: '12px' }).
    qualitynumberA value between 0 and 1 for JPEG quality (e.g., 0.92). Defaults to 1.0.
    cacheBustbooleanIf true, appends current time as a query string to URL requests. Defaults to false.
    imagePlaceholderstringA data URL for a placeholder image used if fetching an image fails. Defaults to undefined (throws error on failure).
  3. Optimize Ocrad OCR results

    master

    To improve recognition accuracy, follow these guidelines:

    • Character Height: Ensure characters are at least 20 pixels high. If they are smaller, use the --scale option.
    • Character Quality: Avoid merged characters, and avoid using very bold or very light (broken) characters.
    • Input Verification: Always verify the PNM input file quality, as recognition quality depends heavily on the input image quality.
  4. Use js-imagediff Jasmine matchers for unit testing

    master

    If you are using Jasmine for testing, js-imagediff provides two custom matchers to simplify testing Canvas and image-like objects:

    • toImageDiffEqual(expected, tolerance): expects a result to equal another image type. On failure, it displays the expected image, the actual image, and the diff.
    • toBeImageData(): expects a result to be an ImageData object.

    To enable these matchers, add them in your beforeEach block:

    beforeEach(function () {
      this.addMatchers(imagediff.jasmine);
    });
  5. Convert DOM nodes to SVG or Raw Pixel Data

    master

    Get an SVG data URL with a filter: You can provide a filter function in the options to exclude specific elements from the output.

    function filter (node) {
        return (node.tagName !== 'i');
    }
    
    domtoimage.toSvg(document.getElementById('my-node'), {filter: filter})
        .then(function (dataUrl) {
            /* do something */
        });

    Get raw pixel data (Uint8Array): Returns a Uint8Array where every 4 elements represent the RGBA data of a pixel.

    var node = document.getElementById('my-node');
    
    domtoimage.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 */
                pixelAtXY = pixels.slice(pixelAtXYOffset, pixelAtXYOffset + 4);
              }
            }
        });
    domtoimage.toSvg(document.getElementById('my-node'), {filter: filter})
        .then(function (dataUrl) {
            /* do something */
        });
  6. Convert DOM nodes to PNG, Blob, or JPEG

    master

    All top-level functions accept a DOM node and an optional rendering options object. They return Promises that resolve with the resulting data URL or blob.

    Get a PNG data URL:

    var node = document.getElementById('my-node');
    
    domtoimage.toPng(node)
        .then(function (dataUrl) {
            var img = new Image();
            img.src = dataUrl;
            document.body.appendChild(img);
        })
        .catch(function (error) {
            console.error('oops, something went wrong!', error);
        });

    Get a PNG Blob (useful for downloading):

    domtoimage.toBlob(document.getElementById('my-node'))
        .then(function (blob) {
            window.saveAs(blob, 'my-node.png');
        });

    Get a compressed JPEG:

    domtoimage.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();
        });
    domtoimage.toPng(node)
        .then(function (dataUrl) {
            var img = new Image();
            img.src = dataUrl;
            document.body.appendChild(img);
        });
  7. Configure rendering options for dom-to-image

    master

    When calling conversion methods like toSvg, toPng, toJpeg, or toBlob, you can pass an options object to customize the output:

    OptionTypeDescription
    filterFunctionA function that receives a node. If it returns true, the node (and its children) are included. Not called on the root node.
    bgcolorStringA valid CSS color value for the background.
    widthNumberThe width to apply to the node before rendering.
    heightNumberThe height to apply to the node before rendering.
    styleObjectAn object of CSS properties to be applied to the node's style before rendering.
    qualityNumberA value between 0 and 1 for JPEG image quality (default: 1.0).
    imagePlaceholderStringA dataURL to use as a placeholder if an image fails to fetch.
    cacheBustBooleanIf true, appends a timestamp to request URLs to bypass the cache.

    Note: filter and style are particularly useful for excluding specific elements or forcing specific layouts during the capture process.

  8. Reference the js-imagediff API

    master

    The following functions are available in the imagediff API:

    • createCanvas(): creates a new Canvas element.
    • createImageData(width, height): creates a new ImageData object.
    • isImage(object): tests if an object is an Image.
    • isCanvas(object): tests if an object is a Canvas.
    • isContext(object): tests if an object is a CanvasRenderingContext2D.
    • isImageData(object): tests if an object is ImageData.
    • isImageType(object): tests if an object is any of the above types.
    • toImageData(object): converts an image type object to a new ImageData object.
    • equal(a, b, tolerance): tests image type objects for equality; tolerance is in pixels.
    • diff(a, b, options): performs an image diff on a and b, returning a - b.
      • options.align: set to 'top' to top-align images of different sizes.
    • noConflict(): removes imagediff from the global space and returns the imagediff instance.
    • imageDataToPNG(imageData, outputFile, [callback]) (NodeJS only): renders imageData to a PNG file at outputFile.
  9. Browser compatibility and limitations

    master

    Supported Browsers

    • Chrome: Fully supported (performs best on large DOM trees).
    • Firefox: Supported (tested on version 45+).

    Unsupported Browsers

    • Internet Explorer: Not supported (lacks support for SVG <foreignObject> tag).
    • Safari: Not supported due to strict security models regarding the <foreignObject> tag.
      • Workaround: Use toSvg and render the resulting SVG on the server.

    Important Considerations

    • Tainted Canvases: If the DOM node contains a <canvas> that is tainted (due to CORS), rendering will fail.
    • External Stylesheets: Firefox may have issues with some external stylesheets; errors will be caught and logged.