我不想问像这样的问题的其他人,但是我不是专家,在计算线相交的某些位置时我需要一点帮助。
使用Javascript和一组具有一定宽度和高度的已知矩形节点(节点的x和y位置代表每个节点的中心),我想计算该行的起点和终点的线偏移量,以便这条线只接触节点的边缘。
[_____]---->[_____]
上面的ascii艺术显示了2个矩形节点,中间有一个箭头。箭头在起点或终点均不与节点相交。假设直线始终是水平或垂直,这很容易计算,但是如果直线成一定角度,我仍然希望直线仅接触边缘。
假设下面的ascii艺术中有一个箭头指向目标节点(由管道符号表示)
[_____]
\
\|
[______]
已知变量:
所需的输出:
示例:
{
sourceIntersect: {x, y},
targetIntersect: {x, y}
}
答案 0 :(得分:0)
我发现有一个可以计算两条线的交点的工具。如果我将矩形视为一组4条线,则可以使用line-intersect npm项目获取这4条线之一上的交点。在下面的SO问题中找到了解决方案。
calculating the point of intersection of two lines
这是我的代码的示例:
// first, get the sizes of the element.
// here we use getBoundingClientRect for an SVG
const clientRect = svgRectElement.getBoundingClientRect();
// extract the width and height
const w = clientRect.width;
const h = clientRect.height;
// trg represents the target point from the element above
// the x and y for trg relate to the center of the element
const top = trg.y - h / 2;
const bottom = trg.y + h / 2;
const left = trg.x - w / 2;
const right = trg.x + w / 2;
// a line extends from src{x,y} to trg{x,y} at the center of both rectangles
// another line extends from left to right at the top of the rectangle
const topIntersect = lineIntersect.checkIntersection(src.x, src.y, trg.x, trg.y, left, top, right, top);
// another line extends from top to bottom at the right of the rectangle
const rightIntersect = lineIntersect.checkIntersection(src.x, src.y, trg.x, trg.y, right, top, right, bottom);
// another line extends from left to right at the bottom of the rectangle
const bottomIntersect = lineIntersect.checkIntersection(src.x, src.y, trg.x, trg.y, left, bottom, right, bottom);
// another line extends from top to bottom at the left of the rectangle
const leftIntersect = lineIntersect.checkIntersection(src.x, src.y, trg.x, trg.y, left, top, left, bottom);
// only one of the intersect variables above will have a value
if (topIntersect.type !== 'none' && topIntersect.point != null) {
// topIntersect.point is the x,y of the line intersection with the top of the rectangle
} else if (rightIntersect.type !== 'none' && rightIntersect.point != null) {
// rightIntersect.point is the x,y of the line intersection with the right of the rectangle
} else if (bottomIntersect.type !== 'none' && bottomIntersect.point != null) {
// bottomIntersect.point is the x,y of the line intersection with the bottom of the rectangle
} else if (leftIntersect.type !== 'none' && leftIntersect.point != null) {
// leftIntersect.point is the x,y of the line intersection with the left of the rectangle
}
要获得源节点的交集,我会将其作为trg
参数传递给我的函数,而目标节点将代表src
参数,从本质上诱使系统认为绘制了线条向后。这将提供源节点的交集,该交集在上面的变量trg
中表示。