使用d3 javascript库时,在路径的特定点放置箭头(标记) [英] Putting an arrow (marker) at specific point on a path when using the d3 javascript library

查看:659
本文介绍了使用d3 javascript库时,在路径的特定点放置箭头(标记)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在工作的图形可视化,我使用SVG和D3库。我被设计师问我是否可以将图形边缘的箭头放在对应于线长度的80%的位置。
我可以通过使用 getPointAtLength 方法来实现第一部分 - 获取位置。

I am working currently on a graph visualization and I use SVG and the D3 library. I was asked by our designer if I can put the arrowheads of the edges of the graph on a position corresponding to 80% of length of the lines. I was able to achieve the first part - getting the position - by using the getPointAtLength method.

var svg = d3.select("body").append("svg")
   .attr("width", 960)
   .attr("height", 500)

var path = svg.append("path")
   .attr("d", "M20,20C400,20,20,400,400,400")
   .attr("fill", "none")
   .attr("stroke", "black");

var pathEl = path.node();

var pathLength = pathEl.getTotalLength();

var pathPoint = pathEl.getPointAtLength(pathLength*0.5);

var point = svg.append("svg:circle")
   .style("fill", "red")
   .attr("r", 5)
   .attr("cx", pathPoint.x)
   .attr("cy", pathPoint.y);

这是 jsfidle示例

现在我不知道如何用箭头将箭头附加到这个位置。更重要的是我如何做到这一点,所以我可以更新图的边缘移动相关的节点。
我还没有找到任何答案,markers的例子使用路径属性,如: style('marker-end',url(#end-arrow) em>

Now I wonder how ca I attach an arrowhead to this position with corresponding orientation. More important how can I do this so I can update the edges of the graph when moving the associated nodes. I was not able to find any answer yet, the examples on "markers" are working with path properties like : style('marker-end', "url(#end-arrow)")

推荐答案

首先, SO 。快速回答是 SVG< markers>

(基本)简短的答案:在红点前一点点,测量斜率,在两点之间画一条线。现在问题简化为:如何在直线的末尾添加一个箭头?使用快速回答。

The (basic) short answer: Take a point a little before the red dot, measure the slope and draw a line between the two points. Now the question is simplified to: How do add an arrow to the end of a straight line? Use the quick answer.

将此代码添加到代码中以显示答案: -

Add this to your code to visualize the answer:-

var pathPoint2 = pathEl.getPointAtLength(pathLength*0.78);
var point2 = svg.append("svg:circle")
    .style("fill", "blue")
    .attr("r", 3)
    .attr("cx", pathPoint2.x)
    .attr("cy", pathPoint2.y);

var slope = (pathPoint.y - pathPoint2.y)/(pathPoint.x - pathPoint2.x);
var x0 = pathPoint2.x/2;
var y0 = slope*(x0 - pathPoint.x) + pathPoint.y;

var line = svg.append("svg:path")
    .style("stroke","green")
    .attr("d", "M" + pathPoint.x + "," + pathPoint.y + " L" + x0 +","+ y0);

这篇关于使用d3 javascript库时,在路径的特定点放置箭头(标记)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆