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:
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:
Clone the original DOM node recursively.
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.
Embed web fonts:
find all the
@font-face
declarations that might represent web fontsparse file URLs, download corresponding files
base64-encode and inline content as
data:
URLsconcatenate all the processed CSS rules and put them into one
<style>
element, then attach it to the clone
Embed images:
embed image URLs in
<img>
elementsinline images used in
background
CSS property, in a fashion similar to fonts
Serialize the cloned node to XML.
Wrap XML into the
<foreignObject>
tag, then into the SVG, then make it a data URL.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:
Element to JPEG
To create a JPEG image, use the domtoimage.toJpeg
method:
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:
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
Post a Comment