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