我假设您希望圆圈中有未填充的空间,而不是用部分正方形填充它?如果是这样,则有效的正方形将是所有四个角都在圆内的正方形,因此一个简单的循环将为您找到它们。下面的代码应该可以做到这一点,尽管为了清楚起见,我已经将其拆分,您可能需要进一步压缩它。
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]);
}
}
}