[英]Drawing HTML5 Canvas Circles using a for Loop
I am trying to draw circles using a for loop. 我正在尝试使用for循环绘制圆圈。 It works just fine accept it double draws the last circle.
接受两次都可以画最后一个圆,效果很好。 See this jsfiddle for the example.
有关示例,请参见此jsfiddle 。
If I comment out the last context.stroke();
如果我注释掉最后一个
context.stroke();
in the second 'for' loop the circles display correctly. 在第二个“ for”循环中,圆圈正确显示。 If I leave it in it double draws the last circle making it look bold.
如果我将其保留在其中,则double会绘制最后一个圆圈,使其看起来加粗。
What am I doing wrong? 我究竟做错了什么?
Ken 肯
The duplicate is caused by the extension lines you are drawing after the circles. 重复是由您在圆圈之后绘制的尺寸界线引起的。 Add a
context.beginPath()
call in the last for loop: 在最后一个for循环中添加一个
context.beginPath()
调用:
for(var j = 0; j < circle_Count + 1; j++) {
context.beginPath();
...
Working fiddle: http://jsfiddle.net/kwwqw5n2/3/ 工作提琴: http : //jsfiddle.net/kwwqw5n2/3/
You have to close paths. 您必须关闭路径。
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var box_Height = 50;
// Make Top Rect
context.fillStyle = "#F3E2A9";
context.fillRect(1, 1, canvas.width-1, box_Height-1);
context.strokeRect(0.5, 0.5, canvas.width-1, box_Height);
//Define the circles
var centerY = 25;
var radius = 10;
var circle_Count = 3;
var distance_Between = canvas.width / (circle_Count+1);
//Draw three white circles.
for(var i=0;i<circle_Count;i++){
context.beginPath();
context.arc(distance_Between * (i+1), centerY, radius, 0, 2 * Math.PI, true);
context.fillStyle = 'white';
context.lineWidth = 1;
context.strokeStyle = '#000000';
context.fill();
context.stroke();
context.closePath();
}
//Define the Extension Lines
var Ext_Line_Start_X = 0;
var Ext_Line_Start_Y = box_Height + 4; //The plus is the Gap
var Ext_Line_Length = 60;
//Draw Extension Lines
for(var j=0;j<circle_Count+1;j++){
context.beginPath();
context.moveTo(distance_Between * j + 0.5, Ext_Line_Start_Y);
context.lineTo(distance_Between * j + 0.5, Ext_Line_Start_Y + Ext_Line_Length);
context.stroke();
context.closePath();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.