Skip to content

Instantly share code, notes, and snippets.

@robinhouston
Last active March 31, 2017 00:16
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 robinhouston/403b6650dda997d36a2eda572b6448dc to your computer and use it in GitHub Desktop.
Save robinhouston/403b6650dda997d36a2eda572b6448dc to your computer and use it in GitHub Desktop.
D3 circle transitions: longhand

Implementing the transition the long way round, using transition.tween directly.

Click the circle to restart

<!doctype html>
<html>
<head>
<title>D3 circle transitions</title>
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
html, body, svg {
width: 100%;
height: 100%;
margin: 0;
}
circle {
fill: red;
stroke: black;
opacity: 0.7;
}
</style>
</head>
<body>
<svg><circle cx="30" cy="20" r="5"/></svg>
<script>
var w = window.innerWidth,
h = window.innerHeight,
circle = d3.select("circle");
function clamp(val, min, max) {
return Math.min(max, Math.max(min, val));
}
function x(d) { return clamp(d.x, d.r + 1, w - d.r - 1); }
function y(d) { return clamp(d.y, d.r + 1, h - d.r - 1); }
function r(d) { return d.r; }
circle.datum({ x: 10, y: 10, r: 80 })
.transition().duration(3000)
.tween("grow", function(d) {
var int_x = d3.interpolateNumber(this.getAttribute("cx"), x(d)),
int_y = d3.interpolateNumber(this.getAttribute("cy"), y(d)),
int_r = d3.interpolateNumber(this.getAttribute("r"), r(d));
return (t) => {
this.setAttribute("cx", int_x(t));
this.setAttribute("cy", int_y(t));
this.setAttribute("r", int_r(t));
};
});
circle.node().onclick = function() { window.location.href = ""; };
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment