如何平移一个矩形,始终包围另一个矩形?

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

阅读 1.7k
1 个回答

既然旋转角度相同,那两个矩形就是轴对齐的,只需要判断内部矩形的坐标即可,不需要什么数学知识😈
补充一个简单的例子:

  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);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题