我正在尝试根据从正方形中心以可变 Angular 向外延伸的假想线找到正方形边缘的坐标。该线与正方形边缘的交点就是我需要的坐标。
例如,正方形为 50px X 50px,中心坐标为 (10,10),线与中心的夹 Angular 为顺时针 45 度 Angular ,该线的末端不应突出正方形,我试图找到这条线末端的 x,y 坐标。
我要用它做什么,我希望能够像在 photoshop 中那样旋转 rect() 中的衬垫渐变填充。我也不想使用图书馆,因为我正在尝试“重新发明轮子”,因为我发现这是为我自己学习的最佳方式。
我在 Javascript 中执行此操作。
在此先感谢您的帮助
最佳答案
如果有四个扇区,则必须将矩形分割,然后确定您的线位于哪个扇区。一种方法是使用简单的 if 语句检查 90°、180° 和 270° 的 Angular 值。
获得 Angular 扇区后,您必须将直线的 Angular 与矩形的对 Angular 线 Angular 进行比较,这样您才能确定直线与哪条边相撞。
一旦确定了碰撞边缘,您就可以免费获得其中一个碰撞坐标(左-x、右-x、上-y 或下-y),另一个坐标可以使用三 Angular 函数(正切关系)获得).
您最终会在每个扇区遇到两种基本情况,一种采用相反的边,形成直 Angular 三 Angular 形,形成与垂直边缘之一的碰撞,另一种采用相邻的边。这是第一个扇区(右上象限)的示例
if (lineAngle < rectDiagAngle) {
// For this collision you have the x coordinate, is the same as the
// right edge x coordinate
colX = rectX + rectW;
// Now you need to find the y coordinate for the collision, to do that
// you just need the opposite leg
oppositeLegLength = Math.tan(lineAngle) * (rectW / 2);
colY = rectCenterY - oppositeLegLength;
} else {
// The line collides with the top edge
// For this collision you have the y coordinate, is the same as the
// top edge y coordinate
colY = rectY;
// Now you need to find the x coordinate for the collision, to do
// that you just need the adjacent leg
adjacentLegLength = (rectH / 2) / Math.tan(lineAngle);
colX = rectCenterX + adjacentLegLength;
}
This fiddle取 Angular ,计算碰撞点,然后从矩形中心到碰撞点画一条线。
关于javascript - 查找由与中心的 Angular 定义的正方形边缘的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20884427/