问题描述
在 javascript 中使用画布的常见方法是:
The common approaching to use canvas in javascript is like :
var canvas = document.getElementById('tutorial');
var ctx = canvas.getContext('2d');
但在 Angular2 中我无法获取 HTMLCanvasElement 对象,var "canvas" 只能获取 Angular2 中的 HTMLElement.那么如何在Angular2中使用canvas呢?还有,如何在Angular2中使用TypeScript语言中的第三方javascript?
but in Angular2 I cannot get the HTMLCanvasElement object, the var "canvas" only get the HTMLElement in Angular2. So how to use canvas in Angular2? And furthermore, how to use the third-party javascript in Angular2 with the language TypeScript?
推荐答案
您可以使用 @ViewChild
在您的班级中执行以下操作.
In your class do the following.
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
name: 'my-component',
// notice the variable name myCanvas
template: `<canvas #myCanvas></canvas>`
})
export class myComponent implements AfterViewInit {
// its important myCanvas matches the variable name in the template
@ViewChild('myCanvas')
myCanvas: ElementRef<HTMLCanvasElement>;
public context: CanvasRenderingContext2D;
ngAfterViewInit(): void {
this.context = this.myCanvas.nativeElement.getContext('2d');
}
}
尽量不要使用 document,因为从长远来看它可能会咬你一口.在编译应用程序后,使用 @ViewChild 也比查询 DOM 更有优势.Angular 已经提前知道它需要对哪个元素进行修改,而不必在 DOM 中找到它.
Try to stay away from using document as much as you can, as it could bite you on the long run. Also using @ViewChild has an advantage over querying the DOM, once the application is compiled. Angular already knows ahead of time which element it needs to do the modifications on, rather than having to find it in the DOM.
有关完整示例,请查看此 演示
For a full example check out this demo
更新
对于 Angular 8,您需要像这样使用 ViewChild.
For angular 8 you need to use ViewChild like this.
@ViewChild('myCanvas', {static: false}) myCanvas: ElementRef;
请参阅 如何我在 Angular 8 中为 @ViewChild 使用了新的静态选项?了解更多信息
这篇关于如何在 Angular 中使用画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)