LoginSignup
6
6

More than 5 years have passed since last update.

WebRTCで取得したビデオを画像にする

Posted at

こんな雰囲気で定期的に映像を画像化してimg要素に入れ込むのをやってみます。

画像化できると色々と応用が出来るのでとりあえず作ったサンプルを元に画像化してみます。

元となるコードはこちらです。まずは手元で動かしてみましょう。

相手から送られてきた映像を画像化

画像化はVideo要素 -> Canvas要素 -> img要素といった形で進めます。

完成がこんな感じです

分かりにくいですが、

  • 上段左: video要素(相手側の映像)
  • 上段真ん中: canvas要素
  • 上段右: img要素
  • 下段: video要素(自分の映像)

となっています。

index.html
        <video id="their-video" width="200" autoplay playsinline></video>
        <canvas id="canvas"></canvas><!--canvas要素-->
        <img id="img" width="400px" height="300px" /><!--img要素-->
        <video id="my-video" muted="true" width="500" autoplay playsinline></video>

また、サンプルコードに追記する形になりますが、methodsの中にcreateImage関数を用意します。

canvasにVideo要素の中身を流し込み、最後にimgタグに流し込みます。

app.js
        createImage: function(){
            const canvas = document.getElementById('canvas');
            const ctx = canvas.getContext('2d'); //canvasの描画モードを2Dに指定
            const img = document.getElementById('img');

            //videoの縦幅横幅を取得
            const videoElm = document.getElementById('their-video'); //相手側の映像要素
            const w = videoElm.offsetWidth;
            const h = videoElm.offsetHeight;
            canvas.setAttribute("width", w);
            canvas.setAttribute("height", h);

            ctx.drawImage(videoElm, 0, 0, w, h);
            img.src = canvas.toDataURL('image/png');
        }

あとはcreateImage()の発火をconnect内部などに追記すればOKです。

 connect: function(call){
            call.on('stream', stream => {
                const el = document.getElementById('their-video');
                el.srcObject = stream;
                el.play();
                setInterval(() => this.createImage(), 1000); //追記 createImage関数を1秒ごとに呼び出す
            });
        },

自分の映像のみの場合

相手側がなく、自分の手元の映像を扱いたい場合はtheir-videoをmy-videoにすればOK

app.js
const videoElm = document.getElementById('their-video');       

↓に変更

app.js
const videoElm = document.getElementById('my-video');

この場合は相手と接続しなくて良いのでSkyWayなど利用しなくても出来ます。

6
6
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
6
6