基于canvas的Angular2组件:如何在里面绘制?

lol*_*f64 12 javascript typescript angular

我写了一个基于画布的简单组件,我正在使用随附类(TypeScript代码)中的Input()属性进行调整.我想要做的是在伴侣类中绘制canvas元素,其代码如下:实现它的最简单方法是什么?(请参阅代码中的注释:我想在构造函数的画布中绘制一个蓝色矩形).

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

tos*_*skv 25

您可以使用ViewChild批注来获取canvas元素的实例.之后,这是所有香草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);
    }
}
Run Code Online (Sandbox Code Playgroud)

@ViewChild将返回一个ElementRef您可以从使用获得本地canvas元素nativeElement财产.