Skip to content

Instantly share code, notes, and snippets.

@HarryStevens
Last active January 20, 2020 21:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HarryStevens/678935d06d4601c25cb141bacd4068ce to your computer and use it in GitHub Desktop.
Save HarryStevens/678935d06d4601c25cb141bacd4068ce to your computer and use it in GitHub Desktop.
Axis Transition
license: gpl-3.0
height: 100

When a scale's domain changes, transition the axis.

<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0;
}
</style>
</head>
<body>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script>
const x = d3.scaleLinear();
const xAxis = d3.axisBottom(x);
const margin = { left: 20, right: 20 };
const svg = d3.select("body").append("svg");
const g = svg.append("g");
draw();
d3.interval(draw, 3000);
function draw(){
const width = innerWidth - margin.left - margin.right;
const height = innerHeight;
x
.domain([0, random(width * .25, width + width * .75)])
.range([0, width]);
svg
.attr("width", width + margin.left + margin.right)
.attr("height", height);
g
.attr("transform", `translate(${margin.left}, ${height / 2})`)
.transition().duration(2000)
.call(xAxis);
}
// random number function
function random(min, max){
return Math.floor(Math.random() * (max - min + 1) + min);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment