1
1

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 3 years have passed since last update.

W3C準拠のカメラ呼び出し機能をAngular上でシンプルに書いてみる

Last updated at Posted at 2021-05-02

まずはテンプレート部分。とてもシンプルです。

app.component.html
<video autoplay></video>


続きましてts部分。
video.srcObject = stream
のvideo部分がオブジェクトは 「'null' である可能性があります。ts(2531)エラー」で怒られてしまうので
let video = document.querySelector('video')!
というようにvideo の初期化時に!を付けてnullにはなりませんよということを明示的に書く必要がtypescriptだと必要です。W3Cのカメラについて調べるとjs前提の記事しかなかったので地味にこけました。

app.component.ts
import { Component } from '@angular/core';
import { Subject } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  {
  ngOnInit(): void {
    let video = document.querySelector('video')!

    const options = {
      video: true
    }
    navigator.mediaDevices.getUserMedia(options)
    .then(stream => {
      video.srcObject = stream
    })
    .catch((error) =>{
      console.log(error)
    })
  }
}


下記はライブデモです。(stackblitの仕様上?PCからの起動のみ) https://stackblitz.com/edit/angular-ivy-vfwkzg?file=src%2Fapp%2Fapp.component.ts

何故か再起動がstackblitzの場合必要なのでお試しの際はお手数ですが再起動してください。。
image.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?