如何解决如何使用 D3 的链接生成器偏移贝塞尔曲线的源点和目标点?
我正在使用 typescript 和 D3,使用 d3 的 treeLayout 编写一个水平分层树电源双自定义视觉效果,我需要编写一个链接生成器,可以根据用户的意愿绘制贝塞尔曲线、阶梯和对角线链接。
问题(对我而言)是:由于节点是具有特定宽度的矩形,因此链接应该从 (source.x + width/2,y) 到 (target.x - width/2,y)。我设法使用 diagonal 和 step 选项,使用 d3.line() 函数(返回路径字符串),但偶然发现了 bezier 选项和 linkHorizontal 函数(返回 link() 函数)。我已经阅读了整个文档,甚至 d3 代码本身,但到目前为止还没有设法使用它的源、目标和上下文函数来实现我所需要的。
到目前为止,这是我的代码,简化了:
- this.settings.links.style 保存用户的链接选项“bezier”、“curve”或“step”
- this.settings.nodes.width 保存节点的宽度
- this.orientation.x 映射了在 Bostock 的 https://bl.ocks.org/mbostock/3184089 中看到的 x 和 y 函数(原始代码也考虑了其他方向)
const linkH = d3.linkHorizontal().x(d => this.orientation.x(d)).y(d => this.orientation.y(d));
let linkGenerator = this.settings.links.style == "bezier" ? linkH
:
(this.settings.links.style == "step" ?
d => d3.line().curve(d3.curveStep)([[this.orientation.x(d.source) + this.settings.nodes.width / 2,this.orientation.y(d.source)],[this.orientation.x(d.target) - this.settings.nodes.width / 2,this.orientation.y(d.target)]])
:
d => d3.line()([[this.orientation.x(d.source) + this.settings.nodes.width / 2,[this.orientation.x(d.target) - this.settings.nodes.width,this.orientation.y(d.target)]])
)
var links = linkGroup.selectAll("path")
.data(this.viewModel.hierarchy.links())
.enter()
.append("path")
.attr("d",linkGenerator);
解决方法
最终,我想出了这个函数,它解决了同时使用 d3.line() 和 d3.linkHorizontal() 的目标。关键是使用 d3.DefaultLinkObject 的实现,以便我可以使用由 attr("d",f(d)) 传递的原始源和目标。
所以,如果它对任何人有帮助:
class myLinkObject implements d3.DefaultLinkObject {
public source: [number,number];
public target: [number,number];
constructor(s: [number,number],t: [number,number]) {
this.source = s;
this.target = t;
}
}
function linkGenerator(d) {
var deltaX = self.settings.nodes.width / 2;
var pSource: [number,number] = [self.orientation.x(d.source) + deltaX,self.orientation.y(d.source);
var pTarget: [number,number] = [self.orientation.x(d.target) - deltaX,self.orientation.y(d.target);
var points = [pSource,pTarget];
var linkObject: myLinkObject = new myLinkObject(pSource,pTarget);
var path = "";
if (self.settings.links.style == "step") {
var lineGenerator = d3.line().curve(d3.curveStep);
path = lineGenerator(points);
} else if (self.settings.links.style == "diagonal") {
var lineGenerator = d3.line();
path = lineGenerator(points);
} else { // bezier
var linkGen = d3.linkHorizontal().x(d => d[0]).y(d => d[1]);
path = linkGen(linkObject);
}
return path;
}
,
这是一个简单的贝塞尔曲线函数,可以用来代替 D3:
const getBezierPath = (from,to) => {
if (Math.abs(from.x - to.x) > Math.abs(from.y - to.y)) {
const midX = (to.x + from.x) / 2;
return `M ${from.x},${from.y} C ${midX},${from.y} ${midX},${to.y} ${to.x},${to.y}`;
} else {
const midY = (to.y + from.y) / 2;
return `M ${from.x},${from.y} C ${from.x},${midY} ${to.x},${to.y}`;
}
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。