Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

javascript - Display an arrow head in the middle of D3 force layout link

I'm using D3 to draw a force-directed graph, which is very similar to this example: http://bl.ocks.org/mbostock/1153292

I'm trying to place the arrowheads in the middle of the links instead of the end.

Playing with the attr("refX", 0) of the marker doesn't help much, because it's absolute and not relative to the link length - my links have varying lengths.

I've been googling around, and my best idea was to replace link.attr("marker-end", ...) with link.attr("marker-segment", ...) according to this example (look for the crosses in the middle of the graphs). But this doesn't seem to work.. I'm guessing because it's part of SVG2 draft only but my browser supports a lower version? (I'm using the most recent ver of Chrome btw).

How can I place the arrowheads in the middle of the links?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of placing the marker on an end, create your lines (<polyline> or <path>) with a single point in the middle of the line and use marker-mid to apply the arrowheads.

This demo for this answer of mine uses this technique to create multiple interior points along the length of a path along with marker-mid. You would simply be creating a single 'waypoint' instead of many.

Edit: Here's a simple hack to the existing demo showing what I mean:

Demo: http://jsfiddle.net/tk7Wv/2/

Arrowheads in the middle of curves

The only changes are:

  1. Changing marker-end to marker-mid, and
  2. Modifying the path generation code to create two arcs (connected in the middle) instead of one.

It will require some simple trigonometry like Superboggly illustrates to pick an appropriate midpoint based on the amount of bowing you want in your lines.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...