To get started, we need to add a canvas element in our HTML. We’ll also attach a reference variable to the element so that we’ll be able to refer to it from the component class:
<canvas #canvas width="600" height="300"></canvas>
In the component class, we can then use the @ViewChild()
decorator to inject a reference to the canvas.
In Angular 8, a new static
flag has been introduced not to break existing applications. Read more about it here. Since I want access to the canvas in the ngOnInit
hook I set it to true.
@ViewChild('canvas', { static: true })
canvas: ElementRef<HTMLCanvasElement>;
Once the component has initialized, we’ll have access to the Canvas DOM node, as well as its drawing context:
this.ctx = this.canvas.nativeElement.getContext('2d');
Here is the starting code for the component:
import { Component, ViewChild, ElementRef, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<canvas #canvas width="600" height="300"></canvas>
<button (click)="animate()">Play</button>
`,
styles: ['canvas { border-style: solid }']
})
export class AppComponent implements OnInit {
@ViewChild('canvas', { static: true })
canvas: ElementRef<HTMLCanvasElement>;
private ctx: CanvasRenderingContext2D;
ngOnInit(): void {
this.ctx = this.canvas.nativeElement.getContext('2d');
}
animate(): void {}
}
#angular #graphics #fun #canvas