📷 Capture an image of any given HTML element.
npm install html-element-to-image
Codepen: https://codepen.io/Hammster/pen/ZEYvxLa
ESM
<script type="module">
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);
})
</script>
CJS
const nodeToDataURL = require('html-element-to-image');
UMD
Exposes the function
nodeToDataURL
to the window/global
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.
- 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 aforeignObject
, 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
- The canvas is not yet DPI aware
- styles from
html
andbody
can sometimes be overwritten by the Specificity - Lazy loaded components can break rendering
- Shadow DOM