本帖最后由 邓伟 于 2024-4-9 12:48 编辑
以下是一个使用JavaScript实现当前页面截图功能的示例代码:
先看效果:
现代浏览器提供了名为navigator.mediaDevices.getDisplayMedia()的API,它可以用于获取屏幕的媒体流,从而实现截图功能。下面是使用此API实现截图的示例代码:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>屏幕截图</title>
- </head>
- <body>
- <h1>屏幕截图</h1>
- <button onclick="captureScreen()">截图</button>
- <div id="screenshotContainer"></div>
- <script>
- async function captureScreen() {
- try {
- const stream = await navigator.mediaDevices.getDisplayMedia({ video: true });
- const videoTrack = stream.getVideoTracks()[0];
- const imageCapture = new ImageCapture(videoTrack);
- const bitmap = await imageCapture.grabFrame();
- const canvas = document.createElement('canvas');
- canvas.width = bitmap.width;
- canvas.height = bitmap.height;
- const ctx = canvas.getContext('2d');
- ctx.drawImage(bitmap, 0, 0);
- const dataURL = canvas.toDataURL('image/png');
- const img = document.createElement('img');
- img.src = dataURL;
- img.style.maxWidth = '100%';
- const screenshotContainer = document.getElementById('screenshotContainer');
- screenshotContainer.innerHTML = '';
- screenshotContainer.appendChild(img);
- videoTrack.stop(); // 停止屏幕共享
- } catch (error) {
- console.error('截图失败:', error);
- }
- }
- </script>
- </body>
- </html>
复制代码
这段代码会在用户点击按钮时调用captureScreen()函数,该函数使用navigator.mediaDevices.getDisplayMedia()获取屏幕的媒体流,并通过ImageCaptureAPI抓取帧。然后,它将抓取的帧绘制到Canvas上,并将Canvas转换为DataURL以显示截图。
|