サンプル
ほぼChatGPTが書きました。
キャプチャ元のブラウザサイズが変化しても問題ナッシングです。
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebRTC + Canvas</title>
<style>
canvas {
border: 1px solid black;
width: 100%;
max-width: 640px;
}
</style>
</head>
<body>
<button id="startCapture">画面キャプチャ開始</button><br>
<video id="video" autoplay playsinline style="display: none;"></video>
<canvas id="canvas"></canvas>
<script src="main.js"></script>
</body>
</html>
main.js
const startButton = document.getElementById('startCapture');
const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let animationFrameId = 0;
async function startCapture() {
try {
cancelAnimationFrame(animationFrameId);
const stream = await navigator.mediaDevices.getDisplayMedia();
video.srcObject = stream;
video.onloadedmetadata = () => {
video.play();
drawToCanvas();
};
} catch (err) {
console.error("画面キャプチャエラー:", err);
}
}
function drawToCanvas() {
// video のサイズが変わっていたら canvas を更新
if (canvas.width !== video.videoWidth || canvas.height !== video.videoHeight) {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
animationFrameId = requestAnimationFrame(drawToCanvas);
}
startButton.addEventListener('click', startCapture);