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?

More than 1 year has passed since last update.

JavaScriptでUSBカメラを使って撮影してみた

Last updated at Posted at 2022-08-31

はじめに

PCに接続されているUSBカメラを起動し、JavaScriptでキャプチャしたものをキャンバス上に描画する処理を書いてみました。
次のhtmlコードをブラウザ上で動作させたら、最初にカメラの許可を求めてくるので、許可してください。

コード

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>カメラ制御</title>
</head>
    <body>
        <div><video id="video-area"></video></div>
        <div><button onclick="captureImage()">キャプチャ</button></div>
        <canvas id="capture-image"></canvas>

        <script>
            const videoArea = document.getElementById('video-area');

            function captureImage() {
                let canvas = document.getElementById('capture-image');
                let cavas2dContext = canvas.getContext('2d');

                canvas.width  = videoArea.videoWidth;
                canvas.height = videoArea.videoHeight;
                cavas2dContext.drawImage(videoArea, 0, 0);
            }

            document.addEventListener('DOMContentLoaded', function() {
                navigator.mediaDevices.getUserMedia({
                    video: true,
                    audio: false
                }).then(stream => {
                    videoArea.srcObject = stream;
                    videoArea.play()
                }).catch(e => {
                    console.log(e)
                });
            });
        </script>
    </body>
</html>

正常に動作すれば以下のように、
緑色の四角に起動したカメラの様子が表示され、青色の四角にキャプチャしたものが描画されます。
image.png

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?