I am currently trying to use the relatively new Screen Capture API. I want the user to open the page, when clicked on a "Start capture" button be prompted with the media selection have the selected media take one screenshot (= record the first frame) and store this image as a base64 without any user interaction (except the permission popup from the browser).
I think I am listening to the wrong event, because when I try to capture the screenshot after the video.onplaying event, it does not work and it only captures a white image and base64.
When I click on the "Capture manually" button it works just fine and as expected.
Can anyone tell me why the code does not work with the event, but only with the explicit button press?
I have created a codepen that shows the problem hopefully: https://codepen.io/luuksen/pen/vYvMdbx?editors=1111
const video = document.getElementById("video");
const canvas = document.getElementById("canvas");
const text = document.getElementById("text");
const startButton = document.getElementById("startButton");
const captureButton = document.getElementById("captureButton");
const context = canvas.getContext("2d");
captureButton.addEventListener("click", function() {
try {
const captureStream = navigator.mediaDevices.getDisplayMedia({
audio: false
}).then(captureStream => {
video.srcObject = captureStream;
return new Promise(resolve => video.onplaying = resolve(captureStream));
}).then((captureStream) => {
// does not work - white image?
takeScreenshot();
})
} catch (err) {
console.error("Error: " + err);
}
});
startButton.addEventListener("click", function() {
// does work
takeScreenshot();
});
takeScreenshot = function() {
canvas.getContext("2d").drawImage(video, 0, 0, 300, 150);
const frame = canvas.toDataURL("image/png");
//captureStream.getTracks().forEach(track => track.stop());
var sScreenshotBase64 = frame;
document.getElementById("text").innerHTML = sScreenshotBase64;
}