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

时间:2016-03-22 19:52:34

标签: 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);
    }
}

1 个答案:

答案 0 :(得分: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);
    }
}

@ViewChild 将返回 ElementRef ,您可以使用 nativeElement 属性从中获取本机canvas元素。< / p>