现代浏览器提供了名为navigator.mediaDevices.getDisplayMedia()的API,它可以用于获取屏幕的媒体流,从而实现截图功能。下面是使用此API实现截图的示例代码:
<!DOCTYPE html>
<html>
<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>