首页 > 解决方案 > 在 Angular 中使用视频和画布元素

问题描述

我正在尝试按照某些 Google 开发人员教程中的建议使用 drawImage 获取流并渲染它。我不断收到错误:

TypeError:无法在“CanvasRenderingContext2D”上执行“drawImage”:提供的值不是类型“(CSSImageValue 或 HTMLImageElement 或 SVGImageElement 或 HTMLVideoElement 或 HTMLCanvasElement 或 ImageBitmap 或 OffscreenCanvas)”

几个小时后,我仍然无法弄清楚为什么,所以我想我会寻求帮助。附上我的代码...

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


@Component({
  selector: 'app-scanner',
  templateUrl: './scanner.component.html',
  styleUrls: ['./scanner.component.css']
})
export class ScannerComponent implements OnInit {
  constructor() {}

  @ViewChild('mycanvas') mycanvas: ElementRef;
  @ViewChild('myvideo') myvideo: ElementRef;
  ctx;

  ngOnInit() {
    this.drawOnCanvas();
  }

  drawOnCanvas() {
    this.ctx = this.mycanvas.nativeElement.getContext('2d');

    navigator.mediaDevices
      .getUserMedia({
        audio: false,
        video: true
      })
      .then(stream => {
        this.myvideo.nativeElement.srcObject = stream;
        this.drawCanvas();
        //this.myvideo.nativeElement.play();
      });
  }

  drawCanvas() {
    this.mycanvas.nativeElement.width = this.myvideo.nativeElement.clientWidth;
    this.mycanvas.nativeElement.height = this.myvideo.nativeElement.clientHeight;
    this.ctx.drawImage(
      this.myvideo.nativeElement.srcObject,
      0,
      0,
      this.mycanvas.nativeElement.width,
      this.mycanvas.nativeElement.height
    );
  }
}
<div>
  <canvas #mycanvas id="mycanvasid"></canvas>
  <video #myvideo></video>
</div>

标签: angularhtml5-canvashtml5-video

解决方案


你似乎没有开始你的流...

当我使用它时

html

  <div id="inner_video" >
      <video #video id="video" autoplay></video>
  </div>

  <canvas #canvas id="canvas" width="1024" height="768">canvas</canvas>      

ts

 @ViewChild("video")
  public video: ElementRef;

  @ViewChild("canvas")
  public canvas: ElementRef;

  ngOnInit() {
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
      navigator.mediaDevices.getUserMedia({ video: true }).then(stream => {
          this.video.nativeElement.srcObject = stream;
          this.video.nativeElement.play();
      });
    }
  } 

捕获代码

 capture(event) {
    event.preventDefault();
    var context = this.canvas.nativeElement.getContext("2d").drawImage(this.video.nativeElement, 0, 0, 1024, 768);
    var picture: any = this.canvas.nativeElement.toDataURL("image/png");
    ...
  }

推荐阅读