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

11,277

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);
Share:
11,277
karlitos
Author by

karlitos

German coming originally from Czech Republic. Professional Web Developer. Open-Source supporter and occasional contributor. Software architecture and DevOps enthusiast with a one good eye for pixel-perfect design. "Happy are those who dream dreams and are ready to pay the price to make them come true." Leon J. Suenes

Updated on July 20, 2022

Comments

  • karlitos
    karlitos almost 2 years

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

  • Ankit Tyagi
    Ankit Tyagi almost 10 years
    This is exactly what i am looking for. Thanks ;)