10

I have weird situation with canvas element and method captureStream. According to documentation HTMLCanvasElement has a method captureStream. However my Angular6 app claims that there isn't such method.

So this code won't work:

let canvas: HTMLCanvasElement;
canvas = document.createElement('canvas');
let stream = canvas.captureStream(20);

It fails on third line.

This code runs without any error:

   let canvas: any;
   canvas = document.createElement('canvas');
   let stream = canvas.captureStream(20);

How this is possible? I'm 100% sure that HTMLCanvasElement has this method and the document.createElement('canvas') returns HTMLCanvasElement.

0

3 Answers 3

8

You can extend an exiting interface in TypeScript and cast your Element to the custom interface.

Example:

interface CanvasElement extends HTMLCanvasElement {
  captureStream(frameRate?: number): MediaStream;
}

const myCanvas = <CanvasElement> document.createElement('canvas');
const myStream = myCanvas.captureStream();
2
  • 1
    better yet: interface CanvasElement extends HTMLCanvasElement { captureStream(int): MediaStream; }then getTracks from the returned object Aug 17, 2020 at 21:02
  • 3
    Better yet, convert all of your TS files to JS files and go back to happy carefree days of ESLint only and no "lost man hours thanks to TypeScript compile problems". Oct 12, 2020 at 6:05
7

According to MDN, it looks like the captureStream method is still a working draft (as of June 2021), eventhough it is not implemented by all major browsers. That is probably why it is not yet part of the type definition for HTMLCanvasElement.

1
  • MaciejWójcik This is the reason for your problem. Please accept it as an answer so @5th gets appropriate credit Dec 6, 2018 at 15:50
7

Available in your entire project without creating a new interface:

declare global {
   interface HTMLCanvasElement {
     captureStream(frameRate?: number): MediaStream;
  }
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.