Как исправить _this.video не определено - PullRequest
0 голосов
/ 11 июня 2019

Я пытаюсь конвертировать утилиту для захвата видео, изначально написанного на Javascript, в Angular.

Я получаю ошибку _this.video is undefined. Оригинальная упаковка здесь: https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Taking_still_photos.

Вот моя попытка конвертировать его в Angular:

capture-image.component.html:

<div class="camera">
  <video id="video" [(ngModel)]="video" (canplay)="setVideo()" name="video" ngDefaultControl>Video stream not available.</video>
  <button id="startbutton" [(ngModel)]="startbutton" (click)="takePicture()" name="startbutton" ngDefaultControl>Take photo</button>
</div>

<canvas id="canvas" [(ngModel)]="canvas" name="canvas" ngDefaultControl></canvas>
<div class="output">
  <img id="photo" [(ngModel)]="photo" name="photo" ngDefaultControl alt="The screen capture will appear in this box.">
</div>

capture-image.component.ts:

@Component({
  selector: 'app-capture-image',
  templateUrl: './capture-image.component.html',
  styleUrls: ['./capture-image.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CaptureImageComponent),
      multi: true
    }
  ]
})

export class CaptureImageComponent implements OnInit {
  video: HTMLVideoElement;
  canvas;
  photo;
  startbutton;
  streaming = false;
  width = 320;
  height = 0;

  constructor() { }

  ngOnInit() {
    navigator.mediaDevices.getUserMedia({video: true, audio: false})
      .then((stream) => {
        this.video.srcObject = stream;  // <-- GETTING ERROR HERE
        this.video.play();
      })
      .catch(function(err) {
        console.log(err);
      });
      // this.clearPhoto();

  }


  setVideo() {
    if (!this.streaming) {
      this.height = this.video.videoHeight/ (this.video.videoWidth/this.width);
      this.video.width = this.width;
      this.video.height = this.height;
      this.canvas.width = this.width;
      this.canvas.height = this.height;
      this.streaming = true; 
    }
  }

  clearPhoto() {
    let context = this.canvas.getContext('2d');
    context.fillStyle = "#AAA";
    context.fillRect(0,0,this.canvas.width, this.canvas.height);

    var data = this.canvas.toDataURL('image/png');
    this.photo.src = data;
  }

  takePicture() {
    let context = this.canvas.getContext('2d');
    if (this.width && this.height) {
      this.canvas.width = this.width;
      this.canvas.height = this.height;
      context.drawimage(this.video, 0, 0, this.width, this.height);

      let data = this.canvas.toDataURL('image/png');
      this.photo.src = data;
    } else {
      this.clearPhoto();
    }
  }


}

Это моя первая попытка этого проекта, и я уверен, что в моем коде есть еще много других проблем, кроме ошибки _this.video undefined. Большое спасибо, если есть идеи, как исправить ошибку _this.video undefined, или для выявления любых других проблем.

1 Ответ

1 голос
/ 11 июня 2019

Вам нужно будет использовать ElementRef , чтобы разрешить прямые ссылки на ваши HTML-элементы в вашей DOM.

Во-первых, в вашем component.html мы используем ссылочную переменную шаблона # и устанавливаем ее как videoRef

<video #videoRef [(ngModel)]="video" (canplay)="setVideo()" name="video" ngDefaultControl>Video stream not available.</video>

Далее на вашем component.ts,

import { Component, ViewChild, ElementRef } from '@angular/core';

...

export class AppComponent {
  @ViewChild('videoRef') videoRef: ElementRef ;
    constructor() { }

  ngOnInit() {
    navigator.mediaDevices.getUserMedia({video: true, audio: false})
      .then((stream) => {
         this.videoRef.nativeElement.srcObject = stream;  // <-- GETTING ERROR HERE
         this.videoRef.nativeElement.play();
      }).catch(function(err) {
        console.log(err);
      });
   // this.clearPhoto();

  }


}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...