Skip to content

Instantly share code, notes, and snippets.

@GitNoise
Last active December 21, 2018 11:50
Show Gist options
  • Save GitNoise/60d83a3f13352fada6ebe221d9939a3b to your computer and use it in GitHub Desktop.
Save GitNoise/60d83a3f13352fada6ebe221d9939a3b to your computer and use it in GitHub Desktop.
rotate text
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
rect { stroke: black; }
text { fill: red; text-anchor: middle }
circle { fill: orange; stroke: steelblue; }
</style>
</head>
<body>
<script>
const data = [
{ id: 0, total: 100, text: "cheese", },
{ id: 1, total: 200, text: "apple",},
{ id: 2, total: 50, text: "bread",},
{ id: 3, total: 100, text: "ginger",},
];
const width = 800;
const height = 300;
const margin = 50;
const scaleY = d3.scaleLinear()
.domain([0,200])
.range([margin, height - margin]);
const scaleX = d3.scaleLinear()
.domain([0, data.length])
.range([margin, width - margin]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
svg.append("g").classed("texts", true)
.selectAll("text")
.data(data, d => d.id).enter()
.append("text")
.attr("x", (d, i) => scaleX(i))
.attr("y", scaleY.range()[1] / 2)
.text(d => d.text);
svg.select("g.texts").selectAll("text")
.each(function() {
const bbox = d3.select(this).node().getBBox();
svg.append("circle")
.attr("cx", bbox.x + bbox.width / 2)
.attr("cy", bbox.y + bbox.height / 2)
.attr("r", 5);
});
setTimeout(() => {
svg.select("g.texts").selectAll("text")
.transition().delay(2000).duration(2000)
.attr("transform", function(d, i) {
const bbox = d3.select(this).node().getBBox();
return `rotate(90, ${ bbox.x + bbox.width / 2}, ${ bbox.y + bbox.height / 2})`;
});
}, 0);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment