为什么我的 for 循环没有在 html canvas 草图中绘制多个重复的形状?
Why my for loop is not drawing multiple repeated shapes in the html canvas sketch?
<html>
<body>
<canvas width = "1200" height = "1200"> </canvas>
<script>
let canvas = document.querySelector('canvas');
let context = canvas.getContext('2d');
context.fillStyle = '#5bd75b';
context.fillRect(0, 0, 1200, 1200);
let radius = 500;
for (let i = 1; i <= 10; i++)
{
if (Math.random() >= 0.5)
{
context.fillStyle = 'yellow';
}
else
{
context.fillStyle = 'red';
}
context.arc(600, 600, radius / i, 0, Math.PI * 2);
context.fill();
}
</script>
</body>
</html>
我正在尝试绘制多个圆圈,这些圆圈会随着循环运行而变小,但我得到的只是一个大圆圈,您能找出我的代码或逻辑有什么问题吗?我厌倦了尝试和寻找解决方案,因为我的循环格式似乎是正确的。
使用 canvas 路径函数时,您需要指定路径何时开始和何时结束。
如果不这样做,所有 context.arc
调用将合并到一个大路径中,每次都会用最后给定的颜色填充。
这是您问题的解决方案:
context.beginPath();
context.arc(600, 600, radius / i, 0, Math.PI * 2);
context.fill();
context.closePath();
<html>
<body>
<canvas width = "1200" height = "1200"> </canvas>
<script>
let canvas = document.querySelector('canvas');
let context = canvas.getContext('2d');
context.fillStyle = '#5bd75b';
context.fillRect(0, 0, 1200, 1200);
let radius = 500;
for (let i = 1; i <= 10; i++)
{
if (Math.random() >= 0.5)
{
context.fillStyle = 'yellow';
}
else
{
context.fillStyle = 'red';
}
context.arc(600, 600, radius / i, 0, Math.PI * 2);
context.fill();
}
</script>
</body>
</html>
我正在尝试绘制多个圆圈,这些圆圈会随着循环运行而变小,但我得到的只是一个大圆圈,您能找出我的代码或逻辑有什么问题吗?我厌倦了尝试和寻找解决方案,因为我的循环格式似乎是正确的。
使用 canvas 路径函数时,您需要指定路径何时开始和何时结束。
如果不这样做,所有 context.arc
调用将合并到一个大路径中,每次都会用最后给定的颜色填充。
这是您问题的解决方案:
context.beginPath();
context.arc(600, 600, radius / i, 0, Math.PI * 2);
context.fill();
context.closePath();