这是一个可以实现您所要求的解决方案。
我已经声明了 3 个“类”以使内容更清晰易读。首先,我定义了一个通用形状类。接下来,我定义了一个基本的圆形类。最后,我定义了一个 vec2 类。您可以像我所做的那样轻松扩展它,并添加从形状类继承的其他形状 - 即正方形三角形等。
我在随机位置和半径处创建 10 个圆。然后我在每个圆圈和它后面的圆圈之间画一条线。我没有为“环绕”的情况而烦恼,所以我画了 10 圈和 9 条线(我不从圈 9 画到圈 0)
我使用了一些 Tamura 留下的代码,因此熟悉的画布尺寸和 id。
<!doctype html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e)}
window.addEventListener('load', onDocLoaded, false);
var shapeList = [];
function onDocLoaded()
{
var i, n=10;
var canvas = byId('myCanvas');
for (i=0; i<n; i++)
{
shapeList[i] = new circle_t(Math.random()*578, Math.random()*400, Math.random()*30 + 20);
shapeList[i].draw(canvas);
}
for (i=0; i<n-1; i++)
draw_line2(shapeList[i].origX, shapeList[i].origY, shapeList[i].radius, shapeList[i+1].origX, shapeList[i+1].origY, shapeList[i+1].radius);
}
var shape_t = function(x,y)
{
this.origX = (x==undefined ? 0 : x);
this.origY = (y==undefined ? 0 : y);
}
shape_t.prototype =
{
origX:0, origY:0, typeString:'shape',
setPos: function(x,y){this.x=x;this.y=y;},
setType: function(typeString){this.typeString = typeString;},
toString: function(){return this.typeString + " - " + this.origX + "," + this.origY;},
draw: function(canElem){},
};
function circle_t(x,y,radius)
{
this.origX = (x==undefined ? 0 : x);
this.origY = (y==undefined ? 0 : y);
this.radius = (radius==undefined ? 10 : radius);
this.setType("circle");
}
circle_t.prototype = new shape_t();
circle_t.prototype.constructor = circle_t;
circle_t.prototype.draw = function(canElem, color)
{
var ctx = canElem.getContext('2d');
var col = 'black';
if (color != undefined)
col = color;
drawCircle(this.origX, this.origY, this.radius, ctx, col);
}
circle_t.prototype.setRadius = function(radius)
{
if (radius != undefined)
this.radius = radius;
}
function drawCircle(x, y, radius, ctx, col)
{
ctx.save();
if (col == undefined)
col = 'black';
ctx.strokeStyle = col;
ctx.lineWidth = 1;
ctx.beginPath();
ctx.arc(x,y,radius,(Math.PI/180)*0, (Math.PI/180)*360, false);
ctx.stroke();
ctx.closePath();
ctx.restore();
}
// define a vec2 class to make vector maths easier (simpler to read)
function vec2(x,y)
{
this.length = function()
{
return Math.sqrt((this.x * this.x) + (this.y*this.y));
}
this.normalize = function()
{
var scale = this.length();
this.x /= scale;
this.y /= scale;
}
this.x = x;
this.y = y;
}
function draw_line2(center1_x, center1_y, radius1, center2_x, center2_y, radius2)
{
var betweenVec = new vec2(center2_x - center1_x, center2_y - center1_y);
betweenVec.normalize();
var p1x = center1_x + (radius1 * betweenVec.x);
var p1y = center1_y + (radius1 * betweenVec.y);
var p2x = center2_x - (radius2 * betweenVec.x);
var p2y = center2_y - (radius2 * betweenVec.y);
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.beginPath();
context.moveTo(p1x,p1y);
context.lineTo(p2x,p2y);
context.stroke();
}
</script>
</head>
<body>
<canvas id="myCanvas" width="578" height="400"></canvas>
</body>
</html>
现场演示请看这里:http://jsfiddle.net/YYjYL/