2016-03-22 15 views
11

私はコンパニオンクラス(TypeScriptコード)内のInput()プロパティでサイズを変更しているキャンバスに基づいて単純なコンポーネントを書きました。私がしたいのは、コンパニオンクラス内にキャンバス要素を描画することです。そのコードは以下のとおりです。これを実現する最も簡単な方法は何ですか? (コード内のコメントを参照してください:コンストラクタからキャンバスの内側に青い四角形を描きたいと思います)。キャンバスに基づくAngular2コンポーネント:内部を描画する方法は?

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); 
    } 
} 

答えて

22

あなたのcanvas要素のインスタンスをつかむためにViewChildアノテーションを使用することができます。それ以来、それはすべてバニラ・ジャズです。

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); 
    } 
} 

はあなたがnativeElementプロパティを使用しているから、ネイティブcanvas要素を取得することができElementRefを返します@ViewChild。

+0

ありがとうございました。しかし、chessCanvas変数は未定義です。 ngAfterViewInitの – loloof64

+0

には、どこかにタイプミスがある可能性があります。私はコンポーネントをセットアップし、それが動作することを確認します。 :) – toskv

+0

ありがとう、私もそれを見つけることを試みています。 – loloof64

関連する問題