123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- /**
- * rect: [left, top, w, h]
- * radar: [radarX, radarY]
- * angle: 0, 90, 180, 270
- * 返回旋转后的矩形 [left, top, w, h]
- */
- function rotateRect(rect, radar, angle) {
- const [left, top, w, h] = rect;
- const [cx, cy] = radar;
- // 矩形四个角
- const corners = [
- [left, top],
- [left + w, top],
- [left + w, top + h],
- [left, top + h]
- ];
- const newCorners = corners.map(([x, y]) => {
- const dx = x - cx;
- const dy = y - cy;
- let nx, ny;
- switch (angle) {
- case 0:
- nx = dx;
- ny = dy;
- break;
- case 90:
- nx = dy;
- ny = -dx;
- break;
- case 180:
- nx = -dx;
- ny = -dy;
- break;
- case 270:
- nx = -dy;
- ny = dx;
- break;
- default:
- throw new Error("angle must be 0, 90, 180, 270");
- }
- return [cx + nx, cy + ny];
- });
- const xs = newCorners.map(p => p[0]);
- const ys = newCorners.map(p => p[1]);
- const newLeft = Math.min(...xs);
- const newTop = Math.min(...ys);
- const newW = Math.max(...xs) - newLeft;
- const newH = Math.max(...ys) - newTop;
- return [newLeft, newTop, newW, newH];
- }
- // 测试
- const rect = [0, 0, 2, 1];
- const radar = [2, 1];
- [0, 90, 180, 270].forEach(angle => {
- const newRect = rotateRect(rect, radar, angle);
- console.log(`angle=${angle}:`, newRect);
- });
- // 预期输出
- // angle=0: [0, 0, 2, 1]
- // angle=90: [2, -1, 1, 2]
- // angle=180: [2, 1, 2, 1]
- // angle=270: [1, 1, 1, 2]
|