为了满足您的需求,我们可以利用现代浏览器支持的 WebRTC 功能和 API。它允许开发者在不使用不再受支持的闪存的情况下获取用户媒体(网络摄像头),并共享用户的屏幕。我们要使用的是后者。
要求
给定的解决方案可以在支持 WebRTC 的浏览器上运行(最新的 Chrome、Firefox、Edge 和 Opera 肯定可以运行)。
对于任何 WebRTC 功能,您必须在 HTTPS 页面上工作。即使是为了当地的发展。如果没有 https,这些功能将被禁用,您的浏览器将在控制台中提示错误。出于安全考虑,将其用于 iframe 可能会很棘手。例如,由于同源策略,stackoverflow 上的代码 sn-p 将不起作用。
显然,用户必须明确授予其权限,并且必须选择他想要共享的屏幕,即使他只想共享一个窗口、一个浏览器选项卡(仅限内部文档)或全屏。你无法克服这个决定,它只属于用户。
欲了解更多信息,请参阅Screen Capture API documentation on MDN
工作演示
因此,由于我们可以将实时用户的屏幕作为流获取,因此我们的想法是将此流附加到视频,然后将视频帧捕获到画布中。从画布中,您可以获得所需的所有数据。将它发送到服务器,创建一个 Blob 并允许您的用户下载它或其他任何东西。
<html lang="en">
<body>
<video id="video" style="display:none;" autoplay></video>
<canvas id="screenshot" width="600px" height="400px"></canvas>
<button id="capture">Take screenshot</button>
<script>
const videoElem = document.getElementById("video");
const canvas = document.getElementById("screenshot");
const context = canvas.getContext('2d');
//We don't want the audio, and we want to see the user's cursor
const displayMediaOptions = {
video: {
cursor: "always"
},
audio: false
};
async function takeScreenshot() {
try {
//There, we get a full screen capture in real time using the WebRTC API.
//And we set the video source with the stream in srcObject.
videoElem.srcObject = await navigator.mediaDevices.getDisplayMedia(
displayMediaOptions
);
} catch(err) {
console.error("Error: " + err, err);
}
}
//We want to take our screenshot when our stream is ready
videoElem.addEventListener('playing', () => {
//If we are too fast, we will get the browser-prompted window
//in the screenshot, so we add a little delay.
setTimeout(() => {
context.drawImage(videoElem, 0, 0, canvas.width, canvas.height);
//We got our screenshot, we can stop to capture the user's screen
let tracks = videoElem.srcObject.getTracks();
tracks.forEach(track => track.stop());
videoElem.srcObject = null;
video.pause();
}, 500);
});
document.getElementById('capture').addEventListener('click', takeScreenshot);
</script>
</body>
</html>
这是最简单的方法。它并不完美,还有改进的余地,但你应该明白这一点。