How to use canvas in Angular2?

A general approach to using canvas in javascript is as follows:

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

but in Angular2 I cannot get the HTMLCanvasElement object, var "canvas" only gets the HTMLElement in Angular2. So how to use canvas in Angular2? And besides, how to use third-party javascript in Angular2 with TypeScript language?

+19
source share
2 answers

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

In your HTML, add a link to the template.

<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 not to use the document for as long as it can bite you in the long run. In addition, using @ViewChild takes precedence over querying the DOM after compiling the application. Angular already knows in advance which element it should make changes to, instead of looking for it in the DOM.

Check out this demo for a complete example.


Refresh

For angular 8 you need to use ViewChild like this.

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

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

+54
source

Are you looking for something like this?

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

Source: https://habr.com/ru/post/1268648/


All Articles