我将如何使用循环水平对齐圆圈?

How would I align circles horizontally using loops?

我已经设法让圆圈彼此重叠,但我不知道如何制作不重叠的圆圈线。

这是我目前得到的。

HTML

<!DOCTYPE html>
<html>
    <head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <canvas id="myCanvas" width="800" height="600"></canvas>
    <script src="js/main.js"></script>
</body>
</html>

JavaScript

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext('2d');

for(var i = 0; i < 10; i++) {
    ctx.fillStyle="rgba(0,0,0,0.5)";
    fillCircle(200,200,i*20)
}

var width = window.innerWidth;
var height = 100;

function fillCircle(x, y, radius) {
    ctx.beginPath();
    ctx.arc(x, y, radius, 0, Math.PI * 2);
    ctx.closePath();
    ctx.fill();
}

任何下一个圆的 x 值必须至少是当前和下一个圆半径之和超出当前圆的 x 值。

所以如果:

var currentCircleX=20
var currentCircleRadius=15
var nextCircleRadius=25

然后:

var nextCircleX = currentCircleX + currentCircleRadius + nextCircleRadius

但是如果你也在画圈圈:

由于上下文笔画会延伸一半到定义的路径之外,您还必须为每个圆添加一半的线宽以避免圆接触:

// account for the lineWidth that extends beyond the arc's path
var nextCircleX = 
    currentCircleX + currentCircleRadius + nextCircleRadius + context.lineWidth

示例代码和演示:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

ctx.fillStyle="rgba(0,0,0,0.5)";
var currentCircleX=0;
var currentCircleRadius=0;

for(var i = 0; i < 10; i++) {
  var nextCircleRadius=i*20;
  var nextCircleX=currentCircleX+currentCircleRadius+nextCircleRadius;   
  fillCircle(nextCircleX,200,nextCircleRadius);
  currentCircleX=nextCircleX;
  currentCircleRadius=nextCircleRadius;
}


function fillCircle(x, y, radius) {
  ctx.beginPath();
  ctx.arc(x, y, radius, 0, Math.PI * 2);
  ctx.closePath();
  ctx.fill();
}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>