【问题标题】:Cannot draw 'fillRect' after initial draw on canvas - Angular2+在画布上初始绘制后无法绘制'fillRect' - Angular2 +
【发布时间】: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


    【解决方案1】:

    画布的分辨率是它的html宽度和高度,而不是css的宽度和高度。因此,除非您在 canvas html 元素上设置宽度和高度,否则画布的内部分辨率将为 300x150。由于您的两个矩形都从 y 至少为 200 开始,因此它们被绘制在画布之外。

    您可以通过暂时将 width="600" height="600" 添加到 canvas html 元素来进行测试。

    但这仅对测试有好处,因为图像会因 css 大小和 html 大小之间的差异而失真,因此最好将画布的宽度和高度设置为其计算出的宽度和高度,例如:

    canvas.width = canvas.offsetWidth;
    canvas.height = canvas.offsetHeight;
    

    在此处查看工作示例:https://jsfiddle.net/7au2mv6f/

    当然,该示例仅在您运行时获取画布的当前大小。调整窗口大小时,您可能需要调整画布大小(并重绘)。

    【讨论】:

    • 成功了!非常感谢你的解释很有意义。我为画布的宽度和高度添加了双向绑定,然后将宽度和高度设置为window.innerWidth * .8
    猜你喜欢
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-08
    • 1970-01-01
    • 2013-07-29
    相关资源
    最近更新 更多