How to superimpose a canvas on an HTML5 video using object-fit cover?


How to superimpose a canvas on an HTML5 video using object-fit cover?



I am refactoring this code: https://github.com/idevelop/predator-vision to superimpose heatmap on a video (with any resolution and aspect-ratio).



I have the following html code:


<div id="videos" class="embed-responsive">
<canvas id="heatmap" class="embed-responsive-item"></canvas>
<video id="remote-video" autoplay muted playsinline class="embed-responsive-item"></video>
</div>



CSS:


#remote-video {
display: block;
height: 100%;
max-height: 100%;
max-width: 100%;
position: absolute;
top: 0;
left: 0;
object-fit: cover;
/* no letterboxing */
opacity: 1;
-moz-transform: rotateY(180deg);
-ms-transform: rotateY(180deg);
-o-transform: rotateY(180deg);
-webkit-transform: rotateY(180deg);
transform: rotateY(180deg);
transition: opacity 1s;
width: 100%;
}

#remote-video.active {
opacity: 1;
}

#heatmap {
display: block;
height: 100%;
max-height: 100%;
max-width: 100%;
position: absolute;
top: 0;
left: 0;
object-fit: cover;
/* no letterboxing */
opacity: 1;
-moz-transform: rotateY(180deg);
-ms-transform: rotateY(180deg);
-o-transform: rotateY(180deg);
-webkit-transform: rotateY(180deg);
transform: rotateY(180deg);
transition: opacity 1s;
width: 100%;
}

#heatmap.active {
opacity: 1;
z-index: 1;
}

#videos {
font-size: 0;
/* to fix whitespace/scrollbars problem */
height: 100%;
pointer-events: none;
position: absolute;
transition: all 1s;
width: 100%;
}

#videos.active {
-moz-transform: rotateY(180deg);
-ms-transform: rotateY(180deg);
-o-transform: rotateY(180deg);
-webkit-transform: rotateY(180deg);
transform: rotateY(180deg);
}



Javascript:



I am rendering the canvas using:


context.drawImage(video, 0, 0, video.videoWidth, video.videoHeight,
0, 0, canvas.width, canvas.height);



Where canvas.width and canvas.height are initially set from video.offsetWidth and video.offsetHeight respectively.



When I render this code the canvas is not exactly superimposed on the video. I am not sure how to fix this.



Note: Canvas seems to superimpose properly if I use object-fit=fill for the video. But the video is stretched.





It seems like the actual video file is not the same resolution as your canvas. You could test that using hard-coded resolutions in your CSS - use px values instead of %. Or you can make the height dependent on the width to keep the html responsive.
– Kokodoko
Jul 1 at 8:17










By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

List of Kim Possible characters

Audio Livestreaming with Python & Flask

NSwag: Generate C# Client from multiple Versions of an API