Javascript: html2canvas with videos

protium - Sep 21 '18 - - Dev Community

If you ever used html2canvas to get a "screenshot" of your web app you probably know that html2canvas doesn't work with videos yet, it renders a blank square. They are working in this feature (I think). So lets write a workaround in the meantime.

Before calling html2canvas method we need to take a capture of each video. By reading some source code and issues in the github repository I discovered that html2canvas renders all the images it finds, so if we have an image as background of your video it will render it in the final canvas.



let canvas = document.getElementById('canvas') // declare a canvas element in your html
let ctx = canvas.getContext('2d');
let videos = document.querySelectorAll('video')
let w, h
for (let i = 0, len = videos.length; i < len; i++) {
    const v = videos[i]
    if (!v.src) continue // no video here
    try {
        w = v.videoWidth
        h = v.videoHeight
        canvas.width = w
        canvas.height = h
        ctx.fillRect(0, 0, w, h)
        ctx.drawImage(v, 0, 0, w, h)
        v.style.backgroundImage = `url(${canvas.toDataURL()})` // here is the magic
        v.style.backgroundSize = 'cover' 
        ctx.clearRect(0, 0, w, h); // clean the canvas
    } catch (e) {
        continue
    }
}


Enter fullscreen mode Exit fullscreen mode

One problem we can see so far is the backgroundSize style. It may not be the same size as your video so you should do some adjustment.

Next use html2canvas as usual



html2canvas(document.body)
    .then((canvas) => {
        // display, save as jpeg
     })


Enter fullscreen mode Exit fullscreen mode

Tested with the latest version v1.0.0-alpha.12

Here a working example
Edit n9wrv84jlj

Why do I need to take screenshot of my web app?

Well there may be many reasons but my first thought would be user privacy violation!. But as I work in a project for a Digital Signage Company I learned that Screenshots are a mandatory feature. Users want to see what's being (or was) displayed in their remote displays anytime.

That's it, I hope someone in the cyberspace will find this useful
(my first post, yaaaai)

. . . . . . . . . . . . . . . . . . . . . . . . . . . .