Skip to content

Instantly share code, notes, and snippets.

@d3noob
Last active January 13, 2022 22:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save d3noob/10633421 to your computer and use it in GitHub Desktop.
Save d3noob/10633421 to your computer and use it in GitHub Desktop.
Interactive text rotation with d3.js
license: mit

This is a simple example of implimenting an HTML input using a <range> input tag and using that to adjust a d3.js drawn svg element (rotate text).

It is used as an example and described in the book D3 Tips and Tricks.

<!DOCTYPE html>
<meta charset="utf-8">
<title>Input test</title>
<p>
<label for="nAngle"
style="display: inline-block; width: 240px; text-align: right">
angle = <span id="nAngle-value"></span>
</label>
<input type="range" min="0" max="360" id="nAngle">
</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<script>
var width = 600;
var height = 300;
var holder = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
// draw the text
holder.append("text")
.style("fill", "black")
.style("font-size", "56px")
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.attr("transform", "translate(300,150) rotate(0)")
.text("d3noob.org");
// when the input range changes update the angle
d3.select("#nAngle").on("input", function() {
update(+this.value);
});
// Initial starting angle of the text
update(0);
// update the element
function update(nAngle) {
// adjust the text on the range slider
d3.select("#nAngle-value").text(nAngle);
d3.select("#nAngle").property("value", nAngle);
// rotate the text
holder.select("text")
.attr("transform", "translate(300,150) rotate("+nAngle+")");
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment