Skip to content

Instantly share code, notes, and snippets.

@cybersiddhu
Forked from satomacoto/labeledarrow.html
Last active August 29, 2015 14:22
Show Gist options
  • Save cybersiddhu/649a7f63b2fc9faabe7c to your computer and use it in GitHub Desktop.
Save cybersiddhu/649a7f63b2fc9faabe7c to your computer and use it in GitHub Desktop.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="http://d3js.org/d3.v2.js"></script>
<style>
line.arrow {
stroke: #666;
stroke-width: 1px;
}
marker#arrow {
fill: #666;
}
.link-label {
font-family: sans-serif;
font-size: 11px;
}
</style>
</head>
<body>
<script>
var nodes = [{x:80,y:150}, {x:40,y:10}, {x:200,y:30}];
var links = [{s:0,t:1,label:"foo"}, {s:0,t:2,label:"bar"}];
var w = 300;
var h = 300;
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
// define marker
svg.append("svg:defs").selectAll("marker")
.data(["arrow"])
.enter().append("svg:marker")
.attr("id", String)
.attr("viewBox", "0 -5 10 10")
.attr("refX", 10)
.attr("refY", 0)
.attr("markerWidth", 10)
.attr("markerHeight", 10)
.attr("orient", "auto")
.append("svg:path")
.attr("d", "M0,-5L10,0L0,0");
svg.selectAll("line")
.data(links)
.enter()
.append("svg:line")
.attr("x1", function(d) { return nodes[d.s].x; })
.attr("y1", function(d) { return nodes[d.s].y; })
.attr("x2", function(d) { return nodes[d.t].x; })
.attr("y2", function(d) { return nodes[d.t].y; })
.attr("class", "link arrow")
.attr("marker-end", "url(#arrow)");
svg.selectAll("text")
.data(links)
.enter()
.append("svg:g")
.append("svg:text")
.text(function(d) { return d.label; })
.attr("class", "link-label")
.attr("text-anchor", "middle")
.attr("transform", function(d) {
var dx = (nodes[d.t].x - nodes[d.s].x),
dy = (nodes[d.t].y - nodes[d.s].y);
var dr = Math.sqrt(dx * dx + dy * dy);
var offset = (1 - (1 / dr)) / 2;
var deg = 180 / Math.PI * Math.atan2(dy, dx);
var x = (nodes[d.s].x + dx * offset);
var y = (nodes[d.s].y + dy * offset);
return "translate(" + x + ", " + y + ") rotate(" + deg + ")";
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment