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

Angularでカメラ撮影してみる

Last updated at Posted at 2021-05-03

前回の続きになります。
https://qiita.com/NoOne/items/42918d1f4f4e3fe59329


まずはテンプレート。今回は撮影ボタンと撮影した画像を表示するcanvasを用意します。
app.component.html
<div class="container">
    <video autoplay class="video"></video>
    <button id="capture" class="btn btn-success cap-btn" (click)="captureImg()">撮影</button>
    <canvas id="canvas" class="canvas"></canvas>
</div>


続きましてts。ボタンイベントハンドラを追加しました。
app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  { 
  private video: any;

  //撮影フォーム設定
  ngOnInit(): void {
    this.video = document.querySelector('video')!;

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

  //撮影ボタン押下時の処理
  captureImg(){
    let canvas = document.getElementById('canvas') as HTMLCanvasElement;
    const context = canvas.getContext('2d');
    context?.drawImage(this.video, 0, 0, canvas.width, canvas.height);
  }
  
}



CSSも記述します。最低限携帯でも撮影できることを想定したつくりにしております(本当に最低限です)。
app.component.css
.video {
    border:12px solid #222;
    background: grey;
    height:70%;
    width: 70%;
}

.cap-btn {
    height: 70%;
    width: 70%;
    font-weight: bold;
    font-size: 56px;
}

.canvas {
    border:12px solid #222;
    background: grey;
    height:70%;
    width: 70%;
}


bootstrapも入れてます。
npm install bootstrap@next
index.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>AngularDetectFace</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
  <app-root></app-root>
</body>
</html>

下記はライブデモです。(stackblitの仕様上?PCからの起動のみ) https://stackblitz.com/edit/angular-ivy-bh4pfe?file=src%2Fapp%2Fapp.component.ts
何故かブラウザ(stackblitz内)再起動が必要なのでお試しの際はお手数ですが再起動してください。。 ![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/630191/ae90b239-61f2-2a58-0768-05d269698716.png)
1
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
1
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?