typescript 基于画布的 Angular2 组件:如何在里面绘制?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36163905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular2 component based on canvas : how to draw inside?
提问by loloof64
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).
我编写了一个基于画布的简单组件,我正在使用伴随类(TypeScript 代码)中的 Input() 属性调整其大小。我想做的是在同伴类中绘制画布元素,其代码如下:实现这一目标的最简单方法是什么?(请参阅代码中的注释:我想从构造函数在画布内绘制一个蓝色矩形)。
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);
}
}
回答by toskv
You can use the ViewChildannotation to grab an instance of your canvas element. After that it's all vanilla js.
您可以使用ViewChild注释来获取画布元素的实例。之后就是香草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);
}
}
The @ViewChildwill return an ElementRefyou can obtain the native canvas element from that using the nativeElementproperty.
该@ViewChild将返回一个ElementRef您可以从使用获得本地canvas元素nativeElement财产。