我正在尝试使用以下代码在画布上水平绘制9个圆圈和垂直绘制9个圆圈。
我为此操作插入了一个嵌套的for循环,但不幸的是我只有一个9个圆的水平线。
有人可以帮忙吗?
<canvas id="sCanvas" width="550" height="1000"> </canvas>
<script>
var randomColour;
var size;
var xPos;
var yPos;
var ctx;
var i;
var j;
function drawCircle(size, x, y, randomColour) {
ctx.beginPath();
ctx.arc(x, y, size / 2, 0, 2 * Math.PI, randomColour);
ctx.fill();
ctx.fillStyle = randomColour;
ctx.stroke();
ctx.strokeStyle = randomColour;
}
var c = document.getElementById("sCanvas");
ctx = c.getContext("2d");
xPos = 20;
yPos = 20;
for (j = 0; j < 9; j++) {
randomColour = "hsl(" + 360 * Math.random() + ",50%,50%)";
drawCircle(30, xPos, yPos, randomColour);
xPos += 50;
for (i = 0; i < 9; i++) {
randomColour = "hsl(" + 360 * Math.random() + ",50%,50%)";
drawCircle(30, xPos, yPos, randomColour);
xPos += 50;
}
yPos += 30;
}
</script>
答案 0 :(得分:0)
你必须在每次迭代后重置你的xPos,否则你只是继续向前推进。这将有效:
for (j = 0; j < 9; j++) {
xPos = 20; //Moved this in here from outside
randomColour = "hsl(" + 360 * Math.random() + ",50%,50%)";
drawCircle(30, xPos, yPos, randomColour);
for (i = 0; i < 9; i++) {
randomColour = "hsl(" + 360 * Math.random() + ",50%,50%)";
drawCircle(30, xPos, yPos, randomColour);
xPos += 50;
}
yPos += 50;
}