html-element-to-image
TypeScript icon, indicating that this package has built-in type declarations

2.1.1 • Public • Published

html-element-to-image

📷 Capture an image of any given HTML element.

Install

// npm
npm install html-element-to-image
 
// yarn
yarn add html-element-to-image

📖 Example

Codepen: https://codepen.io/Hammster/pen/ZEYvxLa

ESM

import nodeToDataURL from 'html-element-to-image'
 
const visualSource = document.getElementById('source')
const imageTarget = document.getElementById('target')
const excluded = document.querySelectorAll('.unwanted-element')
 
nodeToDataURL({
  targetNode: visualSource,
  excludedNodes: excluded,
  customStyle: '.highlighted-element { background: red; }'
})
.then((url) => {
  imageTarget.setAttribute('src', url);
})

UMD

Exposes the function nodeToDataURL to the window/global

🔬 Differences to Other Libraries

Compared to html-to-image, dom-to-image and dom-to-image-more this library uses a different approach, which leads to a big performance increase. Instead of making a deep copy of the targeted element with applied styles via el.getComputedStyle(). This library uses the available DOM for serialization. Before and after the serialization, obfuscated classes get added to hide the parts we don't want to be displayed.

Another difference is that this library has no issue at all with SVG Sprite Sheets and ShadowDOM since we use the given DOM already.

🛡️ Limitation

  • 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 variations in browser implementations.
  • Transforms may be affected. Elements that depend on transform-style: preserve-3d; do not work in a foreignObject, everything get flattened. And this is sadly a requirement for creating a image buffer, and also effects html-to-image, dom-to-image and dom-to-image-more
    • this can be avoided partially by adding a fallback z-index

💔 Know Issues

  • The canvas is not yet DPI aware
  • styles from html and body can sometimes be overwritten by the Specificity

Readme

Keywords

none

Package Sidebar

Install

npm i html-element-to-image

Weekly Downloads

13

Version

2.1.1

License

MIT

Unpacked Size

24.6 kB

Total Files

12

Last publish

Collaborators

  • hammster