我正在尝试使用带有循环的javascript画布绘制同心圆。每次绘制时,圆圈都必须是随机颜色。我试图用下面的代码绘制圆圈,但它没有用。谢谢你的帮助!
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
while ( i=50 ; i < 5; i=i-5 ) {
context.beginPath();
context.arc(300, 300, i, 0, 2 * Math.PI, false);
//context.fillStyle = 'green';
//context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();
}
//the code below worked for one circle
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();
</script>
</body>
</html>
答案 0 :(得分:1)
三种印刷类型错误供您考虑:
while
循环是for
循环。在
while ( i=50 ; i < 5; i=i-5 )
将while
替换为for
循环条件为false,因此在修复1后循环永远不会执行。
for( i=50; i < 5; i=i-5)
将i < 5
替换为i > 5
圆圈在画布上,无法看到。仅出于演示目的,请替换
context.arc(300, 300, i, 0, 2 * Math.PI, false);
,比方说,
context.arc(100, 100, i, 0, 2 * Math.PI, false);
删除或完全注释掉&#34;工作&#34;用于删除语法错误的代码示例。
使用线宽为3px的工作示例:
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
for ( i=50 ; i > 5; i=i-5 ) {
context.beginPath();
context.arc(100, 100, i, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill()
context.lineWidth = 3;
context.strokeStyle = '#003300';
context.stroke();
}
&#13;
<canvas id="myCanvas" width="578" height="200"></canvas>
&#13;