Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 canvas element inside the companion class, whose code is below : what is the simplest way to achieve that ? (Please, see the comment in the code : I would like to draw a blue rectangle inside the canvas from the constructor).

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

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

    constructor(){
        this._size = 150;
        // Here I would like to draw a blue rectangle inside the canvas.
    }

    get size(){
        return this._size;
    }

    @Input () set size(newValue: number){
        this._size = Math.floor(newValue);
    }
}
like image 923
loloof64 Avatar asked Mar 22 '16 19:03

loloof64


1 Answers

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.

like image 192
toskv Avatar answered Oct 01 '22 02:10

toskv