0
0

はじめに

フィルターをかけたり、画像処理を加えたりするために

webcamの映像をCanvas要素に描画する方法をまとめておきます。

プロジェクトの作成

getUserMediaでvideoの権限を要求する。

videoのstreamをvideo.srcObjectに設定。

loadeddataのEventでCanvas要素に描画する。

index.js

// 権限を要求
navigator.mediaDevices.getUserMedia({ video: true, audio: false })
  .then(stream => {
    const video = document.getElementById('myVideo'); 
    const canvas = document.getElementById('myCanvas'); 
    const ctx = canvas.getContext('2d');
    video.srcObject = stream;
    // 描画を開始
    video.addEventListener('loadeddata', () => {
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      function draw() {
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        requestAnimationFrame(draw);
      }
      draw();
    });
  })
  .catch(err => {
    console.error('エラー:', err);
  });

下記のようにHTMLを設定する

index.html

<video style="visibility: hidden;height: 0;width: 0;position:
fixed;pointer-events: none;" id="myVideo" muted autoplay playsinline></video>
<canvas id="myCanvas"></canvas>
<script type="module" src="./index.js"></script>

これで実装完了!!

まとめ

Video要素を使う機会がなかったのでいい勉強になりました。📝

上記をベースにしてフィルターや画像処理を実装してみたい。💪

※間違い等ありましたら、ご指摘いただけると助かります。

0
0
2

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