我有一個圓,我需要用矩形填充此圓。這樣的事情: 在圓內對齊矩形
有沒有一些算法,這或建議從哪裏開始? 我使用fabric.js進行繪製。這是playground。但是,這個問題可能更多的是關於數學。我認爲應該有一些公式,我希望。
我有一個圓,我需要用矩形填充此圓。這樣的事情: 在圓內對齊矩形
有沒有一些算法,這或建議從哪裏開始? 我使用fabric.js進行繪製。這是playground。但是,這個問題可能更多的是關於數學。我認爲應該有一些公式,我希望。
我現在要「足夠接近」:從半徑減去矩形長度,然後將結果乘以2π。這是內圈。現在除以矩形的寬度(並向下取整)以得到矩形的數量。用360°除以得到它們的角度。
一個JSBin文件,你提供我已經更新。我已經在很多細節中註釋了代碼,所以我沒有在這裏解釋很多。
var canvas = new fabric.Canvas(document.querySelector('#my-canvas'));
var circleRadius = 250;
var boxHeight = 30;
var boxWidth = 150;
function createCircleAndBoxes(radius, boxHeight, boxWidth) {
var circle = new fabric.Circle({
radius: circleRadius,
fill: '#f3aa25',
stroke: '#333'
});
canvas.add(circle);
// Calculates the center of the circle
circle.left = (canvas.width - circle.width)/2;
circle.top = (canvas.height - circle.width)/2;
// The inner lines of the boxes make a circle
// Calculate the circumference of this circle.
// By dividing the height of the box by the calculated circumference
// We can get the number of boxes needed
var innerCircumference = 2 * Math.PI * (circleRadius - boxWidth);
var roughBoxCount = Math.floor(innerCircumference/boxHeight);
// Each box is placed exactly at the center of the circle
var calculatedTop = circle.top + (circle.height/2) - 1;
var calculatedLeft = circle.left + (circle.width/2) + 1;
// By changing the origin to a negative point away from the box,
// the box is translated. Also, all rotatopms are done from this point
// The trick however is that, the origin point is calculated
// as a percentage of the height and width. For instance, 0.5 means center
// Therefore, we align the origin point with the circle center and
// calculate the offset as a percentage
var calculatedOriginX = (boxWidth - circleRadius)/boxWidth;
var calculatedOriginY = (boxHeight/2)/boxHeight;
// Since we have the number of boxes needed, we can calculate
// what's the angle each box needs to be rotated
var calculatedAngle = 360/roughBoxCount;
// Combine all these, and you got your requirement
for(var i = 0; i<roughBoxCount; i++) {
var rect = new fabric.Rect({
angle: calculatedAngle * i,
top: calculatedTop,
left: calculatedLeft,
centeredRotation: false,
originX: calculatedOriginX,
originY: calculatedOriginY,
width: boxWidth,
height: boxHeight,
fill: '#e3e3e3',
stroke: '#333'
});
canvas.add(rect);
}
}
createCircleAndBoxes(circleRadius, boxHeight, boxWidth);
瞭解平移,旋轉和中心點的計算,這是這種發展的關鍵。我的方法與'user348173'上面的答案略有不同。但我想,都是值得去通過
感謝您的回答,但我不明白的幾個問題。你說減去長方形長度。按照篇幅,你的意思是身高嗎?另一個問題,我必須分成360度嗎?而且,我不明白我如何計算x,y座標。 – user348173
長度我的意思是長邊,內外半徑之差。看着你的JSBin,這是高度,是的。我將盡快用JSBin更新我的答案。 –
非常感謝您的演示和您的時間。我會試着瞭解它是如何工作的。 – user348173