2016-03-22 14 views
11

Ho scritto un componente semplice basato su una tela, che sto ridimensionando con una proprietà Input() all'interno della classe companion (codice TypeScript). Quello che mi piacerebbe fare è disegnare l'elemento canvas all'interno della classe companion, il cui codice è sotto: qual è il modo più semplice per ottenerlo? (Per favore, vedi il commento nel codice: mi piacerebbe disegnare un rettangolo blu all'interno della tela dal costruttore).Componente angolare2 basato su tela: come disegnare all'interno?

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

risposta

22

È possibile utilizzare l'annotazione ViewChild per afferrare un'istanza del vostro elemento canvas. Dopo questo è tutto vaniglia 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); 
    } 
} 

Il @ViewChild restituirà un ElementRef è possibile ottenere l'elemento canvas nativo da che utilizzando il proprietà nativeElement.

+0

Grazie per la risposta. Ma ottengo la variabile chessCanvas come indefinita. – loloof64

+0

in ngAfterViewInit potrebbe esserci un errore di battitura da qualche parte. Installerò un componente e controllerò che funzioni. :) – toskv

+0

Grazie, sto anche cercando di trovarlo. – loloof64

Problemi correlati