Skip to main content

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 nodeof 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-facedeclarations 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.

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...