Convert Figma logo to code with AI

bubkoo logohtml-to-image

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

5,621
521
5,621
139

Top Related Projects

Screenshots with JavaScript

Generates an image from a DOM node using HTML5 canvas

5,251

Native Linux App for UI and UX Design built in Vala and GTK

Bitmap & tilemap generation from a single example with the help of ideas from quantum mechanics

28,665

Javascript Canvas Library, SVG-to-Canvas (& canvas-to-SVG) Parser

Quick Overview

html-to-image is a JavaScript library that converts HTML elements into images. It provides a simple and efficient way to capture screenshots of web content, including complex layouts and styles, directly in the browser without server-side processing.

Pros

  • Cross-browser compatibility, working in modern browsers including Chrome, Firefox, and Safari
  • Supports capturing full page screenshots, including content outside the viewport
  • Handles complex CSS styles, including pseudo-elements and external resources
  • Lightweight and easy to integrate into existing projects

Cons

  • May have performance issues with very large or complex DOM structures
  • Limited support for certain CSS properties and effects (e.g., some filters and blend modes)
  • Potential inconsistencies in font rendering across different platforms
  • Requires additional configuration for handling cross-origin resources

Code Examples

Capturing a simple element as an image:

import { toPng } from 'html-to-image';

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

Capturing a full page screenshot:

import { toJpeg } from 'html-to-image';

toJpeg(document.body, { quality: 0.95 })
  .then((dataUrl) => {
    const link = document.createElement('a');
    link.download = 'full-page-screenshot.jpeg';
    link.href = dataUrl;
    link.click();
  });

Applying filters to the captured image:

import { toCanvas } from 'html-to-image';

const node = document.getElementById('my-node');
toCanvas(node)
  .then((canvas) => {
    const ctx = canvas.getContext('2d');
    ctx.filter = 'grayscale(100%)';
    ctx.drawImage(canvas, 0, 0);
    document.body.appendChild(canvas);
  });

Getting Started

  1. Install the library:

    npm install html-to-image
    
  2. Import and use in your project:

    import { toPng } from 'html-to-image';
    
    const element = document.getElementById('capture');
    toPng(element)
      .then((dataUrl) => {
        console.log('Image generated:', dataUrl);
      })
      .catch((error) => {
        console.error('Generation failed', error);
      });
    
  3. For more advanced usage and options, refer to the library's documentation on GitHub.

Competitor Comparisons

Screenshots with JavaScript

Pros of html2canvas

  • More mature and widely adopted project with a larger community
  • Supports a broader range of CSS properties and rendering scenarios
  • Better performance for complex layouts and large DOM trees

Cons of html2canvas

  • Larger file size, which may impact load times for web applications
  • Less frequent updates and slower bug fix turnaround
  • More complex API, potentially requiring a steeper learning curve

Code Comparison

html2canvas:

html2canvas(document.body).then(function(canvas) {
    document.body.appendChild(canvas);
});

html-to-image:

import { toPng } from 'html-to-image';

toPng(document.body)
  .then(function (dataUrl) {
    var img = new Image();
    img.src = dataUrl;
    document.body.appendChild(img);
  });

Both libraries aim to convert HTML to images, but html2canvas focuses on canvas-based rendering, while html-to-image offers multiple output formats. html2canvas provides more comprehensive rendering support, making it suitable for complex layouts. html-to-image, on the other hand, offers a simpler API and smaller bundle size, which can be advantageous for lighter applications or when quick implementation is needed.

Generates an image from a DOM node using HTML5 canvas

Pros of dom-to-image

  • More established project with a longer history and larger user base
  • Better support for older browsers, including IE9+
  • Smaller bundle size, which can be beneficial for performance-sensitive applications

Cons of dom-to-image

  • Less actively maintained, with fewer recent updates
  • Limited support for complex CSS properties and modern web features
  • May have issues with certain font rendering and SVG elements

Code Comparison

dom-to-image:

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);
    });

html-to-image:

import { toPng } from 'html-to-image';

toPng(node)
  .then((dataUrl) => {
    const img = new Image();
    img.src = dataUrl;
    document.body.appendChild(img);
  })
  .catch((error) => {
    console.error('oops, something went wrong!', error);
  });

Both libraries offer similar APIs for converting DOM elements to images, with html-to-image providing a more modern, modular approach using ES6 imports. html-to-image generally offers better support for modern web technologies and more frequent updates, while dom-to-image may be preferable for projects requiring broader browser compatibility or a smaller bundle size.

5,251

Native Linux App for UI and UX Design built in Vala and GTK

Pros of Akira

  • Full-featured vector graphics software with a GUI
  • Designed for creating UI/UX prototypes and mockups
  • Supports complex design workflows and collaboration

Cons of Akira

  • Larger project scope and complexity
  • Requires installation and system dependencies
  • Steeper learning curve for users

Code Comparison

While a direct code comparison isn't relevant due to the different nature of these projects, we can highlight their primary use cases:

html-to-image:

import { toPng } from 'html-to-image';

toPng(document.getElementById('my-node'))
  .then(function (dataUrl) {
    var img = new Image();
    img.src = dataUrl;
    document.body.appendChild(img);
  });

Akira (example of creating a shape):

var rectangle = new Lib.Shapes.Rectangle();
rectangle.position = { x: 100, y: 100 };
rectangle.size = { width: 200, height: 100 };
canvas.add_item(rectangle);

html-to-image is a lightweight JavaScript library for converting HTML to images, while Akira is a comprehensive vector graphics application built with Vala and GTK. html-to-image is ideal for web developers needing quick HTML-to-image conversion, whereas Akira caters to designers creating complex vector graphics and UI prototypes.

Bitmap & tilemap generation from a single example with the help of ideas from quantum mechanics

Pros of WaveFunctionCollapse

  • Generates complex patterns and textures procedurally
  • Versatile application in game development and content generation
  • Produces high-quality, diverse outputs based on simple input samples

Cons of WaveFunctionCollapse

  • More complex to implement and understand compared to HTML-to-image conversion
  • Limited to specific use cases in procedural generation
  • Requires careful input sample preparation for optimal results

Code Comparison

WaveFunctionCollapse:

static int[,] Wave(int MX, int MY, int N)
{
    int[,] wave = new int[MX * MY, N];
    for (int i = 0; i < wave.GetLength(0); i++)
        for (int j = 0; j < N; j++) wave[i, j] = 1;
    return wave;
}

HTML-to-image:

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

The code snippets highlight the different focus areas of the two projects. WaveFunctionCollapse deals with complex array manipulations for pattern generation, while HTML-to-image provides a straightforward API for converting HTML elements to image formats.

28,665

Javascript Canvas Library, SVG-to-Canvas (& canvas-to-SVG) Parser

Pros of fabric.js

  • More comprehensive canvas manipulation library with extensive features for creating and editing complex graphics
  • Supports interactive elements and object manipulation on the canvas
  • Robust documentation and active community support

Cons of fabric.js

  • Steeper learning curve due to its extensive API and features
  • Larger file size, which may impact page load times
  • May be overkill for simple image generation tasks

Code Comparison

html-to-image:

import { toPng } from 'html-to-image';

const node = document.getElementById('my-node');
toPng(node)
  .then(dataUrl => {
    const img = new Image();
    img.src = dataUrl;
    document.body.appendChild(img);
  });

fabric.js:

const canvas = new fabric.Canvas('canvas');
const rect = new fabric.Rect({
  left: 100,
  top: 100,
  fill: 'red',
  width: 20,
  height: 20
});
canvas.add(rect);

Summary

html-to-image is a lightweight library focused on converting HTML to images, while fabric.js is a powerful canvas manipulation library. html-to-image is easier to use for simple image generation tasks, while fabric.js offers more advanced features for interactive graphics and complex canvas manipulations. Choose based on your project's specific requirements and complexity.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

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.

build coverage NPM Package NPM Downloads

MIT License Language PRs Welcome

Install

npm install --save html-to-image

Usage

/* 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');

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:

var node = document.getElementById('my-node');

htmlToImage.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 image base64-encoded data URL and download it (using download):

htmlToImage.toPng(document.getElementById('my-node'))
  .then(function (dataUrl) {
    download(dataUrl, 'my-node.png');
  });

toSvg

Get an SVG data URL, but filter out all the <i> elements:

function filter (node) {
  return (node.tagName !== 'i');
}

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

toJpeg

Save and download a compressed JPEG image:

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();
  });

toBlob

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

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');
   }
  });

toCanvas

Get a HTMLCanvasElement, and display it right away:

htmlToImage.toCanvas(document.getElementById('my-node'))
  .then(function (canvas) {
    document.body.appendChild(canvas);
  });

toPixelData

Get the raw pixel data as a Uint8Array with every 4 array elements representing the RGBA data of a 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);
      }
    }
  });

React

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>
    </>
  )
}

Options

filter

(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,

const filter = (node: HTMLElement) => {
  const exclusionClasses = ['remove-me', 'secret-div'];
  return !exclusionClasses.some((classname) => node.classList?.contains(classname));
}

htmlToImage.toJpeg(node, { quality: 0.95, filter: filter});

or

htmlToImage.toPng(node, {filter:filter})

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:

@font-face {
  name: 'proxima-nova';
  src: url("...") format("woff2"), url("...") format("woff"), url("...") format("opentype");
}

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.

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

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:

It'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.

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 <foreignObject> 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 <style> element, then attach it to the clone
  4. Embed images
    • embed image URLs in <img> elements
    • inline images used in background CSS property, in a fashion similar to fonts
  5. Serialize the cloned node to XML
  6. Wrap XML into the <foreignObject> tag, then into the SVG, then make it a data URL
  7. Optionally, to get PNG content or raw pixel data as a Uint8Array, create an Image element with the SVG as a source, and render it on an off-screen canvas, that you have also created, then read the content from the canvas
  8. Done!

Things to watch out for

  • If the DOM node you want to render includes a <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.
  • Rendering will failed on huge DOM due to the dataURI limit varies.

Contributing

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.

Contributors

License

The scripts and documentation in this project are released under the MIT License

NPM DownloadsLast 30 Days