0

我有一个画布,我想让它成为流并通过 webrtc 将其发送给另一个用户。我可以获取它的流并在视频标签中显示它。

var canvas = document.createElement("CANVAS");
var stream = canvas.captureStream(25);
var track = stream.getVideoTracks()[0];
console.log(track);

正如您在 track Object 中看到的,有一个名为 的属性canvas。它会在我的代码中导致错误,因为我使用了一个不需要MediaStreamTrack包含MediaStreamTrack属性canvas的库。有没有办法摆脱该canvas属性?

我已经尝试删除该属性,但它没有用。而且我也使用了下面的代码,但仍然无法正常工作。

var canvas = document.createElement("CANVAS");
var stream = canvas.captureStream(25);
var track = stream.getVideoTracks()[0];

var {canvas, ...rest} = track;

console.log(canvas);
console.log(rest);

我认为这CanvasCaptureMediaStreamTrack是一个只读变量。我能做些什么?

4

1 回答 1

1

更新您的库可能会很好,因为如果由于添加的属性而失败,那么在将来某个时间将新属性添加到此接口时它会再次失败。

您可以覆盖此属性并将其设置为undefined,使用Object.defineProperty

const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const stream = canvas.captureStream(25);
const track = stream.getVideoTracks()[0];
Object.defineProperty( track, "canvas", { value: undefined } );

console.log( track.canvas, "canvas" in track ); // undefined true

您可以在原型上删除此属性CanvasCaptureMediaStreamTrack(从而将其从所有实例中删除):

if( window.CanvasCaptureMediaStreamTrack ) {
  delete CanvasCaptureMediaStreamTrack.prototype.canvas
}
else { // Firefox has this property on `stream`
  delete CanvasCaptureMediaStream.prototype.canvas;
}
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const stream = canvas.captureStream(25);
const track = stream.getVideoTracks()[0];

console.log( track.canvas, "canvas" in track ); // undefined false

你甚至可以传递一个代理,

const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const stream = canvas.captureStream(25);
const track = stream.getVideoTracks()[0];
const prox = new Proxy( track, {
  get( target, key ) {
    if( key === "canvas" ) {
      return undefined;
    }
    return target[ key ];
  }
});
console.log( prox.canvas, "canvas" in prox, prox.kind ); // undefined false video

但实际上,你不得不求助于这只是非常难闻的气味。一方面,我非常怀疑您的库是否可以与当前的 Firefox 一起使用,它仍然使用已弃用的CanvasCaptureMediaStream界面而不是那个CanvasCaptureMediaStreamTrack

如果你真的需要将 a 转换CanvasCaptureMediaStreamTrack为 bare MediaStreamTrack,那么你可以让浏览器按需要工作两次:

const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const stream = canvas.captureStream(25);
// we need to draw something on the canvas
// for the <video> to start reading our MediaStream
ctx.fillRect(10,10,10,10);

const video = document.createElement("video");
video.muted = true;
video.srcObject = stream;
video.play().then(() => {
  const video_stream = video.captureStream ? video.captureStream() :
    video.mozCaptureStream();
  const track = video_stream.getVideoTracks()[0]
  console.log( track.toString(), track ); // [object MediaStreamTrack], {...}
}).catch(console.error);

于 2021-03-17T06:50:46.433 回答