0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

画面キャプチャをCanvasで表示させる方法

Posted at

サンプル

ほぼ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);
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?