首页 > 解决方案 > HTML Canvas,如何为绘制的圆圈添加边框

问题描述

我在画布游戏中为我的玩家创建了一个类,一个圆圈,我想添加一个实心边框,以便我可以使用 RGBA 在我的游戏中添加一些额外的样式。

在这里查看 MDN 文章: https ://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/strokeStyle

https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors

我应该能够使用 strokeStyle 创建一个边框,但它并没有给我一个带有蓝色边框的白色圆圈的预期结果,只是一个白色圆圈。

是不是边界不是正确的变量?还是我缺少的其他东西?

 class Player {
  constructor(x, y, radius, color, border) {
    this.x = x;
    this.y = y;
    this.radius = radius;
    this.color = color;
    this.border = border;
  }
  draw() {
    context.beginPath();
    context.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
    context.fillStyle = this.color;
    context.strokeStyle = this.border;
    context.fill();
  }
}

let newPlayer1 = new Player(canvas.width / 2, canvas.height / 2, 10, "white", "blue");

function init() {
  newPlayer1 = new Player(canvas.width / 2, canvas.height / 2, 10, "white", "blue");
}

标签: javascriptcanvashtml5-canvas

解决方案


You also need context.stroke(); to draw the stroke (the "border of the circle").


推荐阅读