angular - 在 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>
解决方案
你似乎没有开始你的流...
当我使用它时
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");
...
}
推荐阅读
- python - 尝试使用 matplotlib 绘图时不断出现错误
- tensorflow - NotFoundError:[_Derived_]没有为操作定义梯度:Tensorflow 1.15.0 上的 StatefulPartitionedCall
- c# - 尝试激活时无法解析“System.Net.Http.HttpClient”类型的服务
- python-3.x - 如何将 Python SQLAlchemy ORM 与 MonetDB 和数据库模式一起使用
- python - 用坐标绘制 NetworkX Graph
- json - 发送和接收文件的 Python 格式问题
- r - 如何使用 mutate 创建一个变量,该变量将为我提供 R 中一周的日期?
- reactjs - 浏览时出现白屏
- javascript - 使用虚拟键盘时 useState 的初始值未更新
- r - 在 Shiny 中,如果所选变量是数字变量,如何输出直方图,如果是分类变量,如何输出条形图?