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/0adc30abe8a28c942b92ea2c92d70b22 to your computer and use it in GitHub Desktop.
Save robinhouston/0adc30abe8a28c942b92ea2c92d70b22 to your computer and use it in GitHub Desktop.
Clamp at each tick

Clamp at each tick, rather than clamping the target value.

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 = d3.interpolateObject({
x: this.getAttribute("cx"),
y: this.getAttribute("cy"),
r: this.getAttribute("r")
}, d);
return (t) => {
this.setAttribute("cx", x(int(t)));
this.setAttribute("cy", y(int(t)));
this.setAttribute("r", r(int(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