How to use canvas in Angular2?

2020-02-08 05:32发布

问题:

The common approaching to use canvas in javascript is like :

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

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?

回答1:

If you don't want to upset the angular gods, use @ViewChild

In your HTML add a template reference.

<canvas #myCanvas></canvas>

In your class do the following.

import { ViewChild, ElementRef } from '@angular/core';
...
// Somewhere above your class constructor

@ViewChild('myCanvas') myCanvas: ElementRef;
public context: CanvasRenderingContext2D;


// Somewhere under the class constructor we want to wait for our view 
// to initialize

ngAfterViewInit(): void {
  this.context = (<HTMLCanvasElement>this.myCanvas.nativeElement).getContext('2d');
}

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


Update

For angular 8 you need to use ViewChild like this.

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

See How should I use the new static option for @ViewChild in Angular 8? for more information



回答2:

do you looking for something like this?

var canvas: HTMLCanvasElement = <HTMLCanvasElement> document.getElementById('tutorial');
var ctx: CanvasRenderingContext2D = canvas.getContext("2d");