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

Hum*_*bir 20 javascript html5 canvas

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

Hum*_*bir 23

以下是在HTML5中使用JavaScript绘制圆形的方法.

这是代码:

   var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
      var centerX = canvas.width / 2;
      var centerY = canvas.height / 2;
      var 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();
Run Code Online (Sandbox Code Playgroud)

这是使用JSFiddle的现场演示:http://jsfiddle.net/6yXta/

这是输出的截图:

js帆布圈

  • 例如,如果您想在 for 循环中绘制多个圆,并且在循环后仅填充一次,请确保在调用 arc() 之前使用 `context.moveTo(x, y)`。 (4认同)

Sam*_*Sam 15

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

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()
  }
}
Run Code Online (Sandbox Code Playgroud)

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

let ctx = canvas.getContext('2d')
drawCircle(ctx, 50, 50, 25, 'black', 'red', 2)
Run Code Online (Sandbox Code Playgroud)


Era*_*n W 5

使用新的 Canvas Path2D创建形状更容易,它使用相同的画布绘图 API,并允许将声明与绘图本身分离,并重用复杂的几何图形:

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

let circle = new Path2D();  // <<< Declaration
circle.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);

context.fillStyle = 'blue';
context.fill(circle); //   <<< pass circle to context

context.lineWidth = 10;
context.strokeStyle = '#000066';
context.stroke(circle);  // <<< pass circle here too
Run Code Online (Sandbox Code Playgroud)
body {
margin: 0px;
padding: 0px;
}
Run Code Online (Sandbox Code Playgroud)
<canvas id="myCanvas" width="578" height="200"></canvas>
Run Code Online (Sandbox Code Playgroud)