LoginSignup
8

More than 3 years have passed since last update.

WebRTC を使ってカメラで取得した画像をブラウザ上に表示する

Last updated at Posted at 2019-05-17

下記のような感じでいけました。

index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body>
<video id="video" autoplay playsinline></video>
<button id="start">start camera</button>
<script>
'use strict';

// カメラデバイスの取得に成功したときの処理
function handleSuccess(stream) {
    // HTML 内の video element を取得する。
    const video = document.querySelector('video');
    // video element の srcObject に stream を設定する。
    video.srcObject = stream;
}

// カメラデバイスが取得できなかったときの処理
function handleError(error) {
    console.error(error);
}

async function init(e) {
    const constraints = {
        audio: false,  // オーディオデバイスは使用しない
        video: true // デフォルトのカメラデバイスを使用する
    };

    try {
        // getUserMedia() でカメラデバイスを取得する。
        const stream = await navigator.mediaDevices.getUserMedia(constraints);
        // デバイス取得に成功したとき
        handleSuccess(stream);
    } catch (e) {
        // デバイスの取得に失敗したとき
        handleError(e);
    }
}

// start ボタンを押したらカメラでの撮影を開始する。
document.querySelector('#start').addEventListener('click', function(e){
    init(e);
}); 
</script>
</body>
</html>

最低限、これだけ書けば動くみたい。カメラが複数存在するときは、navigator.mediaDevices.enumerateDevices() を使ってデバイスリストを取得しておき、deviceID を constraints の audio や video に設定してやる必要がある。そのへんはまた次の記事で書・・・きますかねえ?

参考にしたコードはこちら: https://github.com/webrtc/samples/tree/gh-pages/src/content/getusermedia/gum

上記コードは、下記の組合せでは動作することを確認してます。
- chrome (74) + mac os (10.12)
- safari (12) + mac os (10.12)
- chrome (74) + windows 10

この記事を書いた時点では Edge では動きませんでしたが、2020/11 現在は動きました。ブラウザの対応状況はこちら: https://caniuse.com/?search=WebRTC

要 HTTPS

Web サーバなどに index.html を置く場合は、ssl (https) でアクセスしないと、少なくとも chrome では動作しません (Chrome が WebRTC の使用に SSL を要求するため)。ローカルなファイルを開く場合は、chrome でも問題なく動作します。

https な環境を無料で用意する方法で、すぐ思いつくのは以下の通りです。

  • github.io を使う:HTMLを置くだけでよければ、これが一番簡単。
  • heroku を使う:クレジットカードがなくても、無料枠で https のサーバを立てられる。
  • 自宅サーバ + Let's Encrpyt と Dynamic DNS で頑張る:あんまり手軽じゃないけど正攻法。

サンプル

下記で、上記のコードを試せます。
https://royalcrab.github.io/rtc_camera.html

getUserMedia() に対応していないOS/ブラウザの組合せでは動きません。対応表は下記にあります。
- https://developer.mozilla.org/ja/docs/Web/API/MediaDevices/getUserMedia

by kani (2019/2020)

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
8