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

时间:2015-02-17 17:11:29

标签: javascript arrays loops html5-canvas

我设法将圆圈放在彼此之上,但我不知道如何制作一系列不重叠的圆圈。

这是我到目前为止所得到的。

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();
}

1 个答案:

答案 0 :(得分:0)

enter image description here

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

所以如果:

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

,然后

var nextCircleX = currentCircleX + currentCircleRadius + nextCircleRadius

但如果你也在抚摸圈子:

由于上下文笔划将延伸到定义路径的一半之外,因此您还必须为每个圆圈添加一半的lineWidth以避免圆圈接触:

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

示例代码和演示:

&#13;
&#13;
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();
}
&#13;
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
&#13;
<canvas id="canvas" width=300 height=300></canvas>
&#13;
&#13;
&#13;