如何在Angular中使用画布 [英] How to use canvas in Angular

查看:163
本文介绍了如何在Angular中使用画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在javascript中使用canvas的常见方法如下:

The common approaching to use canvas in javascript is like :

var canvas = document.getElementById('tutorial');
var ctx = canvas.getContext('2d');

但是在Angular2中我无法获取HTMLCanvasElement对象,变量"canvas"仅在Angular2中获取HTMLElement.那么如何在Angular2中使用canvas? 而且,如何将Angular2中的第三方javascript与TypeScript语言一起使用?

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?

推荐答案

您可以使用

在您的课堂上,请执行以下操作.

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

更新

对于角度8,您需要像这样使用ViewChild.

For angular 8 you need to use ViewChild like this.

@ViewChild('myCanvas', {static: false}) myCanvas: ElementRef;

请参见应该如何我在Angular 8中为@ViewChild使用了新的静态选项吗?以获取更多信息

这篇关于如何在Angular中使用画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆