0

我有一个 Webcola&D3 svg 图,它们之间有节点和链接。直到今天,节点之间的链接可能是单向的,如果 B 连接到 A,则它只是单向链接。 在此处输入图像描述

今天有人告诉我我需要支持 2 路链接,这意味着 A 可以向 B 发送链接,B 可以向 A 发送链接。

现在我对数学以及如何完成它感到困惑,我使用了一些我发现的算法来绘制链接,直到今天我猜想从节点的中心绘制链接,我需要像这样并行显示 2 路链接: 在此处输入图像描述

这是我用来计算链接位置的算法:

let parent = connection.parent;

        const sx = parent.source.x;
        const sy = parent.source.y;
        const tx = parent.target.x;
        const ty = parent.target.y;

        let angle = Math.atan2(ty - sy, tx - sx);
        const radiusSource = parent.source.radius;
        const radiusTarget = parent.target.radius;

        let x1 = sx + Math.cos(angle) * radiusSource;
        let x2 = tx - Math.cos(angle) * radiusTarget;
        let y1 = sy + Math.sin(angle) * radiusSource;
        let y2 = ty - Math.sin(angle) * radiusTarget;

        angle = angle * 180 / Math.PI;
        let opposite = Math.abs(angle) > 90;

        if (opposite)
            angle -= 180;

        connection.coords = [x1, y1, x2, y2, angle, opposite];
        return connection.coords;

这是函数的一部分,其结果进入路径的“d”属性,如下所示:

.attr('d', `M${x1} ${y1} L ${x2} ${y2}`)

现在 2 路链接的结果是它们相互覆盖,任何人都可以帮我改进这个算法,这样它就会使 2 路链接是并行的吗?

4

1 回答 1

1

更新:链接的位置需要通过考虑偏移量的新弧度来计算,例如:

let parent = connection.parent;

const sx = parent.source.x;
const sy = parent.source.y;
const tx = parent.target.x;
const ty = parent.target.y;
const radiusSource = parent.source.radius;
const radiusTarget = parent.target.radius;

let radian = Math.atan2(ty - sy, tx - sx);
let offset = 0.1 // Offset ratio of radian, can be adjusted
let offsetRadian;

let angle = radian * 180 / Math.PI;
let opposite = Math.abs(angle) > 90;
if (opposite) {
    angle -= 180;
    offsetRadian = radian * (1 + offset);
} else {
    offsetRadian = radian * (1 - offset);
}

let x1 = sx + Math.cos(offsetRadian) * radiusSource;
let y1 = sy + Math.sin(offsetRadian) * radiusSource;

let x2 = tx - Math.sin(offsetRadian) * radiusTarget;
let y2 = ty - Math.cos(offsetRadian) * radiusTarget;

connection.coords = [x1, y1, x2, y2, angle, opposite];
return connection.coords;
于 2017-09-12T08:55:45.837 回答