CanvasCaptureMediaStreamTrack的额外属性



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

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

正如您在轨迹Object中看到的,有一个名为canvas的属性。它会在我的代码中导致错误,因为我使用的库需要MediaStreamTrack,而不是包含canvas属性的MediaStreamTrack。有没有办法摆脱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是一个readOnly变量。我能做什么?

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

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

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兼容,因为Firefox仍然使用不推荐使用的CanvasCaptureMediaStream接口,而不是CanvasCaptureMediaStreamTrack接口。

如果您真的需要将CanvasCaptureMediaStreamTrack转换为裸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);

相关内容

  • 没有找到相关文章

最新更新