如何在 Angular 中使用画布

在 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 使用了新的静态选项?了解更多信息

相关文章