Object to canvas javascript

Viewed 257

I'm testing javascript on a smart TV,

I try to get an object video to canvas. With html5 video tag it works in my browser, but not my smart TV.

But when I try with an object player, I have this error message :

Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)'

after multiple test with (id, object id,object src..) the result is same, i don't know how i can get an Object video to a canvas.

here's a simple html test:

<canvas id="test" width="300" height="300"></canvas>
<div id="test" style="left: 0%; top: 0%; width: 25%; height: 25%; position: fixed;">
    <object type="application/avplayer" style="width: 480px; height: 270px;"></object>
</div>

and the js:

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const video = document.getElementsByTagName('object');
//const video = document.getElementsById('idVideo');
ctx.drawImage(video, 0, 0, canvas.width, canvas.height)

Here's an example of my goal but i can't use video tag : http://jsfiddle.net/on1kh4o0/

Any idea or hack to get the same result with an object?

1 Answers

You can't draw an HTMLObjectElement (<object>) directly on a canvas, it is not defined as a CanvasImageSource.

For info, currently the only objects that are defined as being of this type are

  • HTMLImageElement
  • SVGImageElement
  • HTMLVideoElement
  • HTMLCanvasElement
  • ImageBitmap
  • OffscreenCanvas

And even though it's still only part of a draft specs, it is expected that CSSImageValue also gets added to this list.

But HTMLObjectElement is not part of this list, and certainly will never be.

Indeed, even though you can load a video or an image in an <object>, just like with an <iframe>, you can also load a text or an HTML document or many other document types which can't be drawn on a canvas.


Now to your issue, as has been pointed out in the comments, you are definitely facing an XY problem.

Using a video element is currently the only way to draw a video on a canvas (maybe in the future we'll be able to use the Web-Codecs API too, but that's for the future).

So try to find out why your browser doesn't want to draw this video on the canvas.
Try different videos, from different sources, back in the days some Android browsers were blocking drawing any cross-origin mp4 video on a canvas, maybe you are facing a similar issue, if you can, try to input the video from an <input type="file">.

And if your browser has debugging tools, use them. (For instance if it's based on chromium, you should be able to navigate to chrome://media-internals/ or chrome://inspect which might be bale to lead you to some logs.

But anyway, using an <object> as source here won't help you.

Related