From the MediaStream you get through the Media Capture and Streams API, you can create an ImageCapture instance and call its grabFrame()
method that will produce an ImageBitmap you'll be able to paint on a <canvas>
.
const stream = await navigator.mediaDevices.getDisplayMedia();
const track = stream.getVideoTracks()[0];
const capture = new ImageCapture(track);
// when you need the still image
const bitmap = await capture.grabFrame();
// if you want a Blob version
const canvas = document.createElement("canvas");
canvas.width = bitmap.width;
canvas.height = bitmap.height;
canvas.getContext("bitmaprenderer").transferFromImageBitmap(bitmap);
const blob = await new Promise((res) => canvas.toBlob(res));
Now, I should note that this ideal path is currently only accessible to Chromium based browsers.
For other browsers you'd need to set the srcObject
of an HTMLVideoElement to the MediaStream, and to drawImage
that HTMLVideoElement on a 2D context.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…