【发布时间】:2019-10-02 15:49:31
【问题描述】:
所以我要做的就是用 javascript 在 HTML Canvas 上绘图。
我设法获得了画布,并选择了它的上下文来分隔变量并获得一个初始的、普通的、红色的框来绘制,但之后我似乎无法绘制任何东西。
TypeScript 代码:
export class ClassicComponent implements OnInit, OnDestroy, AfterViewInit {
@ViewChild('tennisCanvas') tennisCanvas: ElementRef;
private canvasCtx: CanvasRenderingContext2D;
private canvasWidth: number;
private canvasHeight: number;
...
ngAfterViewInit() {
this.canvasCtx = (this.tennisCanvas.nativeElement as HTMLCanvasElement).getContext('2d');
this.canvasWidth = (this.tennisCanvas.nativeElement as HTMLCanvasElement).width;
this.canvasHeight = (this.tennisCanvas.nativeElement as HTMLCanvasElement).height;
this.canvasCtx.fillStyle = 'black';
this.canvasCtx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
this.draw();
}
private draw() {
this.canvasCtx.fillStyle = 'white';
this.canvasCtx.strokeRect(255, 210, 200, 200);
this.canvasCtx.fillStyle = 'red';
this.canvasCtx.fillRect(this.canvas.width / 2, 200, 50, 25);
}
HTML:
<canvas id="tennisCanvas" #tennisCanvas>
CSS:
#tennisCanvas{
display: block;
width: 80vw;
margin: auto;
margin-top: 3rem;
height: 80vh;
}
它应该看起来像这样:https://imgur.com/mCnCjBl 但只是画了一个黑色方块。
【问题讨论】:
标签: angular html5-canvas