Reputation: 17945
The important part is to take the screenshot
I came across several questions on stackoverflow addressing this (see above), but did not find any answer that fulfilled both conditions. Instead of trying to add a partial answer for existing questions with slightly different requirements, I am asking this in a separate question instead.
I have so-far found a great explanation on how to acquire and stream pixels from a any window into a video
element, using the Screen Capture API. However, I am missing the next step, where those pixels that are being displayed in a video element are converted into a jpg
or png
file that can be uploaded to a server.
Upvotes: 7
Views: 7416
Reputation: 507
I used tucuxi's answer but it not simple. So I wrote new JS library: screenshot.js.
It's enable to take real screenshot simply.
You load the script:
<script src="https://raw.githubusercontent.com/amiad/screenshot.js/master/screenshot.js"></script>
and take screenshot:
new Screenshot({success: img => {
// callback function
myimage = img;
}});
You can read more options in project page.
Upvotes: 1
Reputation: 17945
This is simpler than it seemed. The missing part, saving a still shot of the video to png, can be achieved with code from this answer. The complete code would be as follows:
const v = document.getElementById("v");
const b = document.getElementById("b");
const i = document.getElementById("i");
navigator.mediaDevices.getDisplayMedia({
audio: false
}).then((r) => {
console.log(r);
v.srcObject = r;
}).catch((e) => {
console.log("this must be run in a secure context. Stack snippets (rightfully) refuse to run this.");
});
b.onclick = () => {
// take screenshot
// from https://stackoverflow.com/a/44325898/15472
let scale = 1;
const canvas = document.createElement("canvas");
canvas.width = v.clientWidth * scale;
canvas.height = v.clientHeight * scale;
canvas.getContext('2d').drawImage(v, 0, 0,
canvas.width, canvas.height);
i.src = canvas.toDataURL();
// you can send i.src here to a server
// stop video
let tracks = v.srcObject.getTracks();
tracks.forEach(track => track.stop());
v.srcObject = null;
}
#v,
#i {
width: 400;
height: 300;
}
#v {
border: 1px solid blue;
}
#i {
border: 1px solid green;
}
<div>
<video id="v" autoplay></video>
<button id="b">take screenshot</button>
<img id="i" src="//:0" />
</div>
Note that StackOverflow does not allow asking for screen-grabbing permissions, and therefore this code does not run here.
Upvotes: 9