Putting an arrow (marker) at specific point on a path when using the d3 javascript library

karlitos picture karlitos · Apr 29, 2013 · Viewed 11.1k times · Source

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);

Here is a jsfidle example

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)")

Answer

Alvin K. picture Alvin K. · May 3, 2013

Firstly, the long answer from SO. The quick answer is 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);