Uncaught TypeError: canvas.captureStream is not a function

901 views Asked by At

new to react, here i am getting live rtsp stream to canvas, i want to captureStream from it and change it to video tag, but for some reason when consoling captureStream i'm getting error: Uncaught TypeError: canvas.captureStream is not a function. I found some answers from stackoverflow but those had it working with one browser and not other, but in my case i am getting that error in every browser (chrome, firefox,safari ), any idea ?

import React, { useRef, useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
import { loadPlayer } from 'rtsp-relay/browser';

const StreamVideo = () => {
  const canvas = useRef(null);

  useEffect(() => {
    if (!canvas.current) throw new Error('Ref is null');

    loadPlayer({
      url: 'ws://.../api/stream',
      canvas: canvas.current,
    });
  }, []);
  var stream = canvas.captureStream(25);
  console.log('canvas element', stream);

  return (
    <div >
      <canvas ref={canvas} />
      <video />
    </div>
  );
};

export default StreamVideo;

1

There are 1 answers

8
Alex Wayne On

Your ref starts out null, so you can't call any methods on it until it has a value. And you must access the current property to get the canvas out of your ref.

You handle this in the effect, but not in your code below the effect.

You also need to type your ref properly so typescript knows what element it's going to have in it.

const canvas = useRef<HTMLCanvasElement>(null);

In this case you can probably get away with calling captureStream with the ?. operator so it it will only be called if canvas exists.

var stream = canvas.current?.captureStream(25);
console.log('canvas element', stream);

Here's an example of a canvas streaming to a video tag.

You have to set the srcObject property of a video tag reference to the created stream. You also need the autoPlay attribute set so the video plays it's stream.