Canvas - Mask a video with alpha data from another video slowly

On my page I have a loop video. When you click Play, another video is masked on top of it, and it slowly appears. In short, I am masking a video with another video (the black / white mask turns into Canvas alpha data)

The tutorial is adapted here.

This works, but the transition / video is incredibly slow because the canvas iterates over all the pixels. Does anyone have any pointers in another way to achieve this or speed up the process?

A working demo of this code can be found here.

HTML:

//Buffer canvas (stacked video's: result + alpha mask) <canvas style="display:none" width="1920" height="2160" id="buffer"> </canvas> //Output canvas (combines mask with video) <canvas class="video__output " width="1920" height="1080" id="output"> </canvas> //buffer canvas uses this video to extract data <video class="" id="video" preload="auto" style="display:none" > <source src="assets/video/masking.mp4" type='video/mp4;codecs="avc1.42E01E"' /> </video> //Video loop always playing <video poster="assets/video/poster_desktop.jpg" class="video--top loop" autoplay loop> <source src="assets/video/loop.mp4" type='video/mp4; codecs="avc1.42E01E"' /> </video> 

JS:

 function processFrame() { buffer.drawImage(video, 0, 0); //Get alphadata let image = buffer.getImageData(0, 0, width, height), imageData = image.data, alphaData = buffer.getImageData(0, height, width, height).data; //Loop through pixels, replace data with alpha channel for (let i = 3, len = imageData.length; i < len; i = i + 4) { imageData[i] = alphaData[i-1]; } //Output to second canvas output.putImageData(image, 0, 0, 0, 0, width, height); requestAnimationFrame(processFrame) } 
+5
source share
1 answer

Option one is to reduce two getImageData() to one call. Get the full bitmap, then use two pointers instead, one pointing to the RGB data, and the second to the beginning of the matte data.

The second option is to consider using the webm video format. This supports alpha channel support . Currently only supported in the Chrome browser (and possibly the newer Opera).

0
source

Source: https://habr.com/ru/post/1244705/


All Articles