【发布时间】:2019-08-24 07:12:48
【问题描述】:
我正在尝试按照某些 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>
【问题讨论】:
-
不要在
ngOnInit中运行drawOnCanvas,而是在ngAfterViewInit 中尝试。当ngOnInit触发时,视图和元素还没有准备好。 -
对不起,我刚刚更新了代码(在我粘贴之前有一个旧副本)我实际上已经尝试过 ngAfterViewInit 并且(现在)仍然遇到同样的错误。
标签: angular html5-canvas html5-video