Skip to content

Instantly share code, notes, and snippets.

@d3noob
Last active September 15, 2020 06:09
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/243271eb4aef4e0f3fc9c0668edac19a to your computer and use it in GitHub Desktop.
Save d3noob/243271eb4aef4e0f3fc9c0668edac19a to your computer and use it in GitHub Desktop.
Input acting on two elements in v6
license: mit

This is a demonstration of the use of the html 'range' input to rotate two text elements using d3.js v6.

This graph is part of the code samples for the update to the book D3 Tips and Tricks to version 6 of d3.js.

<!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://d3js.org/d3.v6.min.js"></script>
<script>
var width = 600;
var height = 300;
var holder = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
// draw d3.js text
holder.append("text")
.attr("class", "d3js")
.style("fill", "black")
.style("font-size", "56px")
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.attr("transform", "translate(300,55) rotate(0)")
.text("d3.js");
// draw d3noob.org text
holder.append("text")
.attr("class", "d3noob")
.style("fill", "black")
.style("font-size", "56px")
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.attr("transform", "translate(300,130) rotate(0)")
.text("d3noob.org");
// when the input range changes update the rectangle
d3.select("#nAngle").on("input", function() {
update(+this.value);
});
// Initial starting height of the rectangle
update(0);
// update the elements
function update(nAngle) {
// adjust the range text
d3.select("#nAngle-value").text(nAngle);
d3.select("#nAngle").property("value", nAngle);
// adjust d3.js text
holder.select("text.d3js")
.attr("transform", "translate(300,55) rotate("+nAngle+")");
// adjust d3noob.org text
holder.select("text.d3noob")
.attr("transform", "translate(300,130) rotate("+(360 - nAngle)+")");
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment