使用 for 循环绘制 HTML5 画布圆圈

Drawing HTML5 Canvas Circles using a for Loop

本文关键字:布圆圈 HTML5 绘制 for 循环 使用      更新时间:2023-09-26

我正在尝试使用 for 循环绘制圆圈。它工作得很好,接受它双重绘制最后一个圆。有关示例,请参阅此 jsfiddle。

如果我注释掉最后一个 context.stroke();在第二个"for"循环中,圆圈正确显示。如果我把它留在里面,它会双画最后一个圆圈,使其看起来很大胆。

我做错了什么?

眼界

重复是由您在圆之后绘制的延长线引起的。在最后一个 for 循环中添加一个context.beginPath()调用:

for(var j = 0; j < circle_Count + 1; j++) {
  context.beginPath();
  ...

工作小提琴:http://jsfiddle.net/kwwqw5n2/3/

你必须关闭路径。

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