Skip to content Skip to sidebar Skip to footer

Angular2 Component Based On Canvas : How To Draw Inside?

I wrote a simple component based on a canvas, which I am resizing with an Input() property inside the companion class (TypeScript code). What I would like to do is to draw the canv

Solution 1:

You can use the ViewChild annotation to grab an instance of your canvas element. After that it's all vanilla js.

import {Component, View, Input, ViewChild, ElementRef} from 'angular2/core';

@Component({
    selector: 'chess-diagram',
})
@View({
    template: `<canvas #chessCanvas class='chess-diag'
     [attr.width]='_size'
     [attr.height]='_size'></canvas>`,
})
export class ChessDiagram {
    private _size: number;

    // get the element with the #chessCanvas on it
    @ViewChild("chessCanvas") chessCanvas: ElementRef; 

    constructor(){
        this._size = 150;
    }

    ngAfterViewInit() { // wait for the view to init before using the element

      let context: CanvasRenderingContext2D = this.chessCanvas.nativeElement.getContext("2d");
      // happy drawing from here on
      context.fillStyle = 'blue';
      context.fillRect(10, 10, 150, 150);
    }

    get size(){
        return this._size;
    }

    @Input () set size(newValue: number){
        this._size = Math.floor(newValue);
    }
}

The @ViewChild will return an ElementRef you can obtain the native canvas element from that using the nativeElement property.


Post a Comment for "Angular2 Component Based On Canvas : How To Draw Inside?"