Dom-to-image is a library which can turn arbitrary DOM node into a vector (SVG) or raster (PNG) image, written in JavaScript.

How to capture an image from a DOM element with javascript

Although if you haven't needed such feature in one of your projects, you'll find this feature really interesting. This library as it's name describes, will generate an image or svg from a node of the document in Base64 format. Yep, every html tag, whatever you want can be rendered into an image with javascript without create external calls to any server or anything on every modern browser.

Requirements

To achieve this task, we are going to depend of the dom-to-image Javascript library. Dom-to-image is a library which can turn arbitrary DOM node into a vector (SVG) or raster (PNG or JPEG) image, written in JavaScript. It's based on domvas by Paul Bakaus and has been completely rewritten, with some bugs fixed and some new features (like web font and image support) added.

You can get the script either using NPM:

npm install dom-to-image

Or just download the .zip file (or navigate) in the official Github repository.

How it works

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.

  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 data: URLs

    • 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.

Implementation

All the top level functions accept a DOM node and rendering options, and return promises, which are fulfilled with corresponding data URLs.

Element to PNG

To create a PNG image, use the domtoimage.toPng method:

<div id="my-node">
    <p>Some HTML content or images.</p>
</div>

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

Element to JPEG

To create a JPEG image, use the domtoimage.toJpeg method:

<div id="my-node">
    <p>Some HTML content or images.</p>
</div>

<script>
    var node = document.getElementById('my-node');
    var options = {
        quality: 0.95 
    };

    domtoimage.toJpeg(node, options).then(function (dataUrl) {
        // Do something with the dataURL (data:image/jpeg;base64,i........)
    });
</script>

Element to Blob

If you need to retrieve a Blob instead of a Base64 string, you can use the domtoimage.toBlob method that returns a Blob in PNG from the rendered DOM:

<div id="my-node">
    <p>Some HTML content or images.</p>
</div>

<script>
    var node = document.getElementById('my-node');
    
    domtoimage.toBlob(node).then(function (blob) {
        window.saveAs(blob, 'my-node.png');
    });
</script>

In the previous example, we use the FileSaver plugin that allow you to download a file (from a Blob) in the Browser with Javascript.

Live example

Give it a try and play with the following fiddle, a base64 image will be appended to the document everytime you click the create button. Change the content of the textarea to seethe result:

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 <foreignObject> tag.

Have fun !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors