Skip to content

Instantly share code, notes, and snippets.

@ezyang
Created December 7, 2012 21:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ezyang/4236639 to your computer and use it in GitHub Desktop.
Save ezyang/4236639 to your computer and use it in GitHub Desktop.
Text rotation in D3.js
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script src="http://d3js.org/d3.v2.js"></script>
</head>
<body>
<script type="text/javascript">
/**
* A convenient function for taking a transformation (with rotation) on
* text and modifying it so that it always results in right-up text.
* Only knows about translate and rotate. Auto-valigns the text.
*/
function textrotate(transform) {
return function (node) {
node.each(function() {
var t = d3.transform(d3.functor(transform).apply(this, arguments));
node.attr("alignment-baseline", "central");
node.style("dominant-baseline", "central");
if (t.rotate <= 90 && t.rotate >= -90) {
node.attr("text-anchor", "begin");
node.attr("transform", t.toString());
} else {
node.attr("text-anchor", "end");
t.rotate = (t.rotate > 0 ? -1 : 1) * (180 - Math.abs(t.rotate));
node.attr("transform", t.toString());
}
});
}
}
var w = 300, h = 300;
var n = d3.select("body").insert("svg")
.attr("width", w)
.attr("height", h)
.insert("g")
.attr("transform","translate(" + w/2 + "," + w/2 + ")");
n.insert("circle")
.attr("r", 5)
.attr("cx", 0)
.attr("cy", 0);
n.insert("text")
.text("This is some text");
function f(rot) {
n.select("text").call(textrotate("rotate("+rot+")translate(12,0)"));
setTimeout(function() { f(rot+1) }, 25);
}
f(0);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment