如何使用 JavaScript 在 HTML5 Canvas 中绘制圆圈?

新手上路,请多包涵

如何使用最少的 JavaScript 代码在 HTML5 Canvas 中绘制一个简单的圆圈?

原文由 Humayun Shabbir 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 587
2 个回答

以下是在 HTML5 中使用 JavaScript 绘制圆圈的方法:

 const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 70;

context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();
 body {
  margin: 0;
  padding: 0;
}
 <canvas id="myCanvas" width="578" height="200"></canvas>

原文由 Humayun Shabbir 发布,翻译遵循 CC BY-SA 4.0 许可协议

我把上面的答案变成了一个有用的函数:

 function drawCircle(ctx, x, y, radius, fill, stroke, strokeWidth) {
  ctx.beginPath()
  ctx.arc(x, y, radius, 0, 2 * Math.PI, false)
  if (fill) {
    ctx.fillStyle = fill
    ctx.fill()
  }
  if (stroke) {
    ctx.lineWidth = strokeWidth
    ctx.strokeStyle = stroke
    ctx.stroke()
  }
}

然后,像这样使用它在坐标 50,50 处绘制一个带有红色描边(宽度 2)的黑色圆圈,半径为 25:

 let ctx = canvas.getContext('2d')
drawCircle(ctx, 50, 50, 25, 'black', 'red', 2)

原文由 Sam 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题