基于canvas的Angular2组件:如何在里面绘制? [英] Angular2 component based on canvas : how to draw inside?

查看:351
本文介绍了基于canvas的Angular2组件:如何在里面绘制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

你可以使用 ViewChild 注释来获取canvas元素的实例。之后就是所有的香草js。

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

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

The @ViewChild will return an ElementRef you can obtain the native canvas element from that using the nativeElement property.

这篇关于基于canvas的Angular2组件:如何在里面绘制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆