如何平移一个矩形,始终包围另一个矩形?
有两个旋转相同角度的矩形,内部的矩形不移动,外围的矩形可以任意移动,内部的矩形不能超出外围的矩形,边重叠时只能沿着边移动,想了很久,没找到其中的数学规律,希望有大神能够指点一二
回复
1个回答

test
2024-07-17
既然旋转角度相同,那两个矩形就是轴对齐的,只需要判断内部矩形的坐标即可,不需要什么数学知识😈补充一个简单的例子:
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
const box = {x:100, y:25, width:100, height:100, rotation:0};
const rect = {x:0, y:0, width:50, height:50}
const ctx = canvas.getContext('2d');
const globalToLocal = (x, y) => {
const cx = box.x + box.width / 2
const cy = box.y+ box.height/ 2
const dx = x - cx
const dy = y - cy
const cos = Math.cos(box.rotation)
const sin = Math.sin(box.rotation)
const rx = dx * cos + dy * sin
const ry = -dx * sin + dy * cos
return { x: rx + cx - box.x, y: ry + cy - box.y }
}
canvas.onmousemove = (e) => {
let {x, y} = globalToLocal(e.offsetX, e.offsetY)
x -= rect.width/2
y -=rect.height/2
if (x < 0) x = 0
if (x > box.width - rect.width) x = box.width - rect.width
if (y < 0) y = 0
if (y > box.height - rect.height) y = box.height - rect.height
rect.x = x
rect.y = y
}
const loop = () => {
box.rotation += 0.001;
ctx.resetTransform();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.translate(box.x +box.width/2,box.y +box.height/2);
ctx.rotate(box.rotation);
ctx.strokeStyle = "red"
ctx.strokeRect(-box.width/2, -box.height/2, box.width, box.height)
ctx.strokeStyle = "blue"
ctx.translate(-box.width/2, -box.height/2);
ctx.strokeRect(rect.x, rect.y, rect.width, rect.height)
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容