Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save chris-creditdesign/85d28e6955962c187959 to your computer and use it in GitHub Desktop.
Save chris-creditdesign/85d28e6955962c187959 to your computer and use it in GitHub Desktop.
Make a bouncing beech ball with D3
var width = window.innerWidth;
var height = window.innerHeight;
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
svg.append("rect")
.attr("width", width)
.attr("height", (height * 0.2))
.attr("y", (height * 0.8))
.attr("fill","khaki");
var ball = svg.append("g")
.attr("transform","translate(" + (width * 0.5) + "," + (height * 0.5) + ")");
ball.append("circle")
.attr("r", "50px")
.attr("fill", "tomato");
ball.append("ellipse")
.attr("rx","50px")
.attr("ry","25px")
.attr("fill", "white");
function bounce() {
ball.transition()
.duration(1500)
.ease("cubic-in")
.attr("transform","translate(" + (width * 0.5) + "," + (height * 0.8) + "), scale(1.1,0.9)")
.transition()
.ease("cubic-out")
.duration(1500)
.attr("transform","translate(" + (width * 0.5) + "," + (height * 0.2) + "), scale(0.9,1.1)")
.each("end", bounce);
};
bounce();
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
body {
margin: 0;
padding: 0;
background-color: lightskyblue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment