tsayen / dom-to-image

Generates an image from a DOM node using HTML5 canvas
Other
10.21k stars 1.68k forks source link

Support replacing node when filter #395

Open compilelife opened 2 years ago

compilelife commented 2 years ago

This pull request introduce supporting for replacing node when doing filter.

The original demand is to use first frame of video instead of blank(transparent) when capturing a node.

See what it can do :

Assuming that we have a node:

<div>
   <p>Hello Video</p>
   <video src='http://mock.video.addr.com/1.mp4'></video>
</div>

A regular call to domtoimage.toPng(theDiv) would result to a image only contain the 'Hello world' text, leave blank for video area.

Now you can do:

const convertVideoToCanvas = (node)=>{
  if (node instanceof HTMLVideoElement) {
    const c = document.createElement('canvas');
    c.width = node.clientWidth;
    c.height = node.clientHeight;
    c.setAttribute('style', c.getAttribute('style') || '')
    const ctx = c.getContext('2d');
    if (ctx) {
      if (node.readyState >= 3) {
        ctx.drawImage(node, 0, 0);
      }
    }
    return c;
  }
  return node
}
const options = {
  filter: convertVideoToCanvas
}
domtoimage.toPng(theDiv, option)

This will create a image contains both text and video.

And you can do other similar node replacing trick.

On the other hand, this patch keep the api compatibility of filter unchanged.

So you can still do boolean filter like you always do:

const option = {
  filter: (node)=>{return node.nodeName !== 'video'}
}