Why is video from canvas.captureStream empty when using drawImage with MediaRecorder

[亡魂溺海] 提交于 2019-12-02 09:29:36

That happens because your image is coming from a cross-domain resource and has tainted your canvas.
Tainting a canvas from which a MediaStream is being captured will stop said MediaStream from capturing any new image.

Also, trying to capture a MediaStream from such a tainted canvas will throw a SecurityError.

const ctx = canvas.getContext('2d');
const stream = canvas.captureStream();
vid.srcObject = stream;

const img = new Image();
img.onload = e => {
  console.log('will taint the canvas')
  ctx.drawImage(img, 0, 0);
  // and if we try now to capture a new stream, we have a clear error
  const stream2 = canvas.captureStream();
}
img.src = "https://66.media.tumblr.com/84d332cafeb1052c477c979281e5713b/tumblr_owe3l0tkCj1wxdq3zo1_1280.jpg";
ctx.fillRect(0,0,20,20);
<canvas id="canvas"></canvas>
<video id="vid" controls autoplay muted></video>

To circumvent it, you need the server to send the image in a cross-origin compliant way, by setting correctly the Access-control-origin headers to accept your own domain, then requesting this image with the crossorigin attribute. The server from which you are loading this particular image does allow anyone to access their data in such a cross-origin compliant way, so we can demonstrate the front-end part:

const ctx = canvas.getContext('2d');
const stream = canvas.captureStream();
vid.srcObject = stream;

const img = new Image();
img.crossOrigin = 'anonymous'; // add this to request the image as cross-origin allowed
img.onload = e => {
  console.log('will not taint the canvas anymore')
  ctx.drawImage(img, 0, 0);
  // and if we try now to capture a new stream, we have a clear error
  const stream2 = canvas.captureStream();
}
img.src = "https://66.media.tumblr.com/84d332cafeb1052c477c979281e5713b/tumblr_owe3l0tkCj1wxdq3zo1_1280.jpg";
ctx.fillRect(0,0,20,20);
<canvas id="canvas"></canvas>
<video id="vid" controls autoplay muted></video>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!