我试图在画布的圆形区域中绘制各种不重叠的正方形。
最初我试图在圆圈内的随机位置创建正方形并检查它们是否重叠,但一段时间后我意识到它对于我需要的东西来说效率太低且太复杂。
我想要一个算法,它使用圆的中心坐标、圆的半径和正方形网格的大小,并返回网格上每个正方形位置的坐标数组,该网格的所有边缘都在圆内.
我假设您希望圆圈中有未填充的空间而不是用部分正方形填充它?如果是这样,有效的正方形将是所有四个角都在圆圈内的正方形,因此一个简单的循环会为您找到它们。下面的代码应该可以做到这一点,尽管为了清楚起见,我已经把它分开了,但你可能想要更浓缩它。
const size = 4; // The size of each square.
const squareCoords = []; // The top-left corners of each valid square.
const circle = [10, 10, 10]; // The circle, in the form [centerX, centerY, radius]
function DistanceSquared(x1, y1, x2, y2) {
return (x2-x1) ** 2 + (y2-y1) ** 2;
}
function isInsideCircle(x, y, cx, cy, r) {
return (DistanceSquared(x, y, cx, cy) <= r ** 2);
}
let topLeftInside = false, bottomRightInside = false, topRightInside = false, bottomLeftInside = false;
for (let xx = circle[0] - circle[2]; xx < circle[0] + circle[2]; xx += size) {
for (let yy = circle[1] - circle[2]; yy < circle[1] + circle[2]; yy += size) {
topLeftInside = isInsideCircle(xx, yy, circle[0], circle[1], circle[2]);
bottomRightInside = isInsideCircle(xx + size, yy + size, circle[0], circle[1], circle[2]);
bottomLeftInside = isInsideCircle(xx, yy + size, circle[0], circle[1], circle[2]);
topRightInside = isInsideCircle(xx + size, yy, circle[0], circle[1], circle[2]);
if (topLeftInside && bottomRightInside && bottomLeftInside && topRightInside) {
squareCoords.push([xx, yy]);
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句