用小圆圈打成一个更大的圆圈

时间:2016-02-23 14:58:35

标签: javascript canvas geometry

我试图找出一种方法将较小的圆圈打包成较大的圆圈,但由于某种原因,较小的圆圈没有正确对齐。

我相信它的位置计算可能会遗漏一些东西。

请参阅代码了解更多详情:



var c_el = document.getElementById("myCanvas");
var ctx = c_el.getContext("2d");

var canvas_width = c_el.clientWidth;
var canvas_height = c_el.clientHeight;
var circle1 = {
	r: 50, /// radius 
	pos: {
		x: (canvas_width / 2),
		y: (canvas_height / 2)
	}
}

var circle2 = {
	r: 5,
	pos:{}
}

var c2h = circle2.r * 2; /// circle height ////
var c2w = c2h; //// circle width /////

var c1h = circle1.r * 2; /// circle height ////
var c1w = c1h; //// circle width /////

var max_circles2_H = c1h / c2h; 

var r = circle1.r;
var d = circle1.r - 2;  //// segement distance from center ////

drawCircle( circle1 );
for(var col = 1; col < max_circles2_H; col++){
	var d = circle1.r - ( col * c2h); /// distance from center to segment ///
	var c = 2 * (Math.sqrt((r*r) - (d * d))); //// circle's chord length
	var max_circles2_W = c / c2w;
	for(var row = 1; row < max_circles2_W; row++){
		circle2.pos.x = (row * c2w) + (circle1.pos.x - circle1.r);
		circle2.pos.y = (col * c2h) + (circle1.pos.y - circle1.r);
		drawCircle(circle2);
	}
}


function drawCircle( circle ){
	ctx.beginPath();
	ctx.arc(circle.pos.x, circle.pos.y, circle.r, 0, 2 * Math.PI);
	ctx.stroke();
}
&#13;
<canvas id="myCanvas" width="300" height="150">
&#13;
&#13;
&#13;

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

这很接近,但需要稍微调整一下。你可以看到x_offset的计算位置,并尝试一些不同的数学来收紧它。

更新 将Math.ceil添加到max_circles2_W,似乎很合适。

&#13;
&#13;
var c_el = document.getElementById("myCanvas");
var ctx = c_el.getContext("2d");

var canvas_width = c_el.clientWidth;
var canvas_height = c_el.clientHeight;
var circle1 = {
	r: 50, /// radius 
	pos: {
		x: (canvas_width / 2),
		y: (canvas_height / 2)
	}
}

var circle2 = {
	r: 5,
	pos:{}
}

var c2h = circle2.r * 2; /// circle height ////
var c2w = c2h; //// circle width /////

var c1h = circle1.r * 2; /// circle height ////
var c1w = c1h; //// circle width /////

var max_circles2_H = c1h / c2h; 

var r = circle1.r;
var d = circle1.r - 2;  //// segement distance from center ////

drawCircle( circle1 );
for(var col = 1; col < max_circles2_H; col++){
	var d = circle1.r - ( col * c2h); /// distance from center to segment ///
	var c = 2 * (Math.sqrt((r*r) - (d * d))); //// circle's chord length
	var max_circles2_W = Math.ceil(c / c2w);
  
    // CALCULATE OFFSET HERE
    var x_offset = Math.floor((c1w - (max_circles2_W * c2w)) / 2);
  
	for(var row = 1; row < max_circles2_W; row++){
		circle2.pos.x = (row * c2w) + (circle1.pos.x - circle1.r) + x_offset;
		circle2.pos.y = (col * c2h) + (circle1.pos.y - circle1.r);
        ctx.fillText(row, circle2.pos.x-3, circle2.pos.y+4);
		drawCircle(circle2);
	}
}


function drawCircle( circle ){
	ctx.beginPath();
	ctx.arc(circle.pos.x, circle.pos.y, circle.r, 0, 2 * Math.PI);
	ctx.stroke();
}
&#13;
<canvas id="myCanvas" width="300" height="150">
&#13;
&#13;
&#13;