Search code examples
javascripthtmlhtml5-canvashtml5-videovideo.js

Draw VideoJS frames by a canvas


It's posted that once you use VideoJS for playing video, you shouldn't touch the <video> tag used by VideoJS never again:

I'm drawing video frames to canvas by such a code taken from here:

document.getElementById("btn").onclick = (evt) => {
  const canvas = document.getElementById("canvas");
  const video = document.querySelector("video#video, #video video");
  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;
  canvas.getContext("2d").drawImage(video, 0, 0);
};
@import url("https://cdnjs.cloudflare.com/ajax/libs/video.js/7.11.7/video-js.min.css");
<script src="https://cdnjs.cloudflare.com/ajax/libs/video.js/7.11.7/video.min.js"></script>
<video class = "video-js vjs-theme-fantasy" vjs-big-play-centered muted controls id="video" data-setup="{}">
  <source src="//vjs.zencdn.net/v/oceans.mp4" type="video/mp4">
  <source src="//vjs.zencdn.net/v/oceans.webm" type="video/webm">
</video>
<button id="btn">draw to canvas</button>
<canvas id="canvas"></canvas>

Problem

The problem is this line of code which gets the <video> element used by VideoJS:

const video = document.querySelector("video#video, #video video");

The above statement is not using VideoJS API. Is there a standard way to do so by VideoJS API? Is there another approach to draw VideoJS to canvas which is more consistent with VideoJS API?


Solution

  • @VC.One comment answers my question:

    There is nothing wrong with accessing the <video> object to draw to <canvas>. VideoJS is just some code for user interface and handling of loading some file types (like M3U8 playlist). I think that Asker was told not to touch the video tag because they were adjusting it ways that clash with VideoJS options (like setting poster in video tag when VideoJS has its own poster option etc)...