Jarkob
Jarkob

Reputation: 78

Adding arrow-ends to D3.js lines

I am working with the following fiddle: https://jsfiddle.net/4ovue3s8/12/

I would like the connections between the nodes to have arrow-ends, like in this one: http://jsfiddle.net/maxl/mNmYH/2/

I added a marker element to the svg like this:

svg.append("defs")
  .append("marker")
  .attr("id", "arrow")
  .attr("markerWidth", 10)
  .attr("markerHeight", 10)
  .attr("refX", 5)
  .attr("refY", 5)
  .attr("orient", "auto")
  .attr("markerUnits", "strokeWidth")
  .append("path")
  .attr("d", "M0,0 L0,6 L9,3 z")
  .attr("fill", "#000");

and then added the marker-end attribute to the lines like this:

links = svg.selectAll( "line.link" )
  .data( json.edges )
  .enter().append( "line" )
  .attr( "class", "link" )
  .attr("marker-end", "url(#arrow)")
  .attr("markerWidth", 5)
  .attr("stroke", "#000")
  .attr("stroke-width", 5)
  .style( "stroke", "#000" )
  .style( "stroke-width", 2 );

This does not show any arrow-ends.

If I add the marker-end attribute to a normal line like this:

svg.append("line")
  .attr("x1", 50)
  .attr("y1", 50)
  .attr("x2", 100)
  .attr("y2", 100)
  .attr("stroke", "#000")
  .attr("stroke-width", 5)
  .attr("marker-end", "url(#arrow)");

it displays.

Upvotes: 3

Views: 8505

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

First make a def for the arrow:

svg.append("svg:defs").append("svg:marker")
    .attr("id", "arrow")
    .attr("viewBox", "0 -5 10 10")
    .attr('refX', -20)//so that it comes towards the center.
    .attr("markerWidth", 5)
    .attr("markerHeight", 5)
    .attr("orient", "auto")
  .append("svg:path")
    .attr("d", "M0,-5L10,0L0,5");

Instead of line make a path

links = svg.selectAll( "line.link" )
    .data( json.edges )
    .enter().append( "path" )//append path
    .attr( "class", "link" )
    .style( "stroke", "#000" )
    .attr('marker-start', (d) -> "url(#arrow)")//attach the arrow from defs
    .style( "stroke-width", 2 );

lastly give d attribute for path in tick function

  links
    .attr( "d", (d) -> "M" + d.source.x + "," + d.source.y + ", " + d.target.x + "," + d.target.y)

working code here

Upvotes: 8

Related Questions