Reputation: 29
So I created a canvas on top of a HTML5 video originally, then I switched the video player from HTML5 to Video.js and I get the error
"Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)' at HTMLCanvasElement.".
The error occurs when I try to actually draw an image.
This is my HTML code using video.js:
<video class = "video-js vjs-theme-fantasy" vjs-big-play-centered muted controls id="video" data-setup="{}">
And this is a small snippet of my Javascript trying to draw the canvas image:
var video = document.getElementById("video");
let screenshot_context = screenshot_canvas.getContext("2d");
screenshot_context.drawImage(video, originX, originY, boxWidth, boxHeight, 0, 0, boxWidth, boxHeight);
I searched online and it seems like using Video.js shouldn't be an issue when trying to use a canvas element and I just wanted to know if anyone who is familiar with both the HTML5 canvas element and Video.js (I am aware it supports the HTML5 video) could confirm that the HTML canvas element is compatible with Video.js as well?
I apologize in advance if it is a silly question, I am new to javascript, still learning the ropes!
Upvotes: 2
Views: 1458
Reputation: 136996
It seems that videojs will wrap your <video> element in a <div> element that will take your <video>'s id
attribute. So when you do document.getElementById("video");
instead of having the expected <video> element, you got that wrapping <div>.
You can workaround that issue by changing this line to something like
const video = document.querySelector("video#video, #video video");
to handle both the case when videojs messed with your document, and when it didn't.
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>
Upvotes: 2