8
我試圖找到一種方法來儘可能多地放置六邊形。到目前爲止,我獲得的最好結果是通過從中心向外以圓形生成六邊形。用六邊形填充圓
但我認爲我的計算,以獲得最大六角圈是錯誤的,特別是部分在那裏我使用Math.ceil()
和Math.Floor
功能向下舍/一些值。
使用Math.ceil()
時,六邊形有時與圓圈重疊。
另一方面,當使用Math.floor()
時,它有時會在最後一圈六邊形和圓形邊界之間留下太多空間。
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 PI=Math.PI;
var PI2=PI*2;
var hexCircle = {
\t r: 110, /// radius
\t pos: {
\t \t x: (canvas_width/2),
\t \t y: (canvas_height/2)
\t }
};
var hexagon = {
\t r: 20,
\t pos:{
\t \t x: 0,
\t \t y: 0
\t },
\t space: 1
};
drawHexCircle(hexCircle, hexagon);
function drawHexCircle(hc, hex) {
\t drawCircle(hc);
\t var hcr = Math.ceil(Math.sqrt(3) * (hc.r/2));
var hr = Math.ceil((Math.sqrt(3) * (hex.r/2))) + hexagon.space; // hexRadius
\t var circles = Math.ceil((hcr/hr)/2);
drawHex(hc.pos.x , hc.pos.y, hex.r); //center hex ///
\t for (var i = 1; i<=circles; i++) {
\t \t for (var j = 0; j<6; j++) {
\t \t \t var currentX = hc.pos.x+Math.cos(j*PI2/6)*hr*2*i;
\t \t \t var currentY = hc.pos.y+Math.sin(j*PI2/6)*hr*2*i;
\t \t \t drawHex(currentX,currentY, hex.r);
\t \t \t for (var k = 1; k<i; k++) {
\t \t \t \t var newX = currentX + Math.cos((j*PI2/6+PI2/3))*hr*2*k;
\t \t \t \t var newY = currentY + Math.sin((j*PI2/6+PI2/3))*hr*2*k;
\t \t \t \t drawHex(newX,newY, hex.r);
\t \t \t }
\t \t }
\t }
}
function drawHex(x, y, r){
ctx.beginPath();
ctx.moveTo(x,y-r);
for (var i = 0; i<=6; i++) {
ctx.lineTo(x+Math.cos((i*PI2/6-PI2/4))*r,y+Math.sin((i*PI2/6-PI2/4))*r);
}
ctx.closePath();
ctx.stroke();
}
function drawCircle(circle){
\t ctx.beginPath();
\t ctx.arc(circle.pos.x, circle.pos.y, circle.r, 0, 2 * Math.PI);
\t ctx.closePath();
\t ctx.stroke();
}
<canvas id="myCanvas" width="350" height="350" style="border:1px solid #d3d3d3;">