block by harrystevens 678935d06d4601c25cb141bacd4068ce

Axis Transition

Full Screen

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

index.html

<!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>