Skip to content

Instantly share code, notes, and snippets.

@winniehell
Last active September 2, 2016 23:15
Show Gist options
  • Save winniehell/742e6b0351d44e909737 to your computer and use it in GitHub Desktop.
Save winniehell/742e6b0351d44e909737 to your computer and use it in GitHub Desktop.
SVG + D3.js: Jumping circles
window.addEventListener('load', function () {
console.log('Powered by d3 v' + d3.version);
var svg = d3.select('svg');
var circles = svg.selectAll('circle')[0];
circles.forEach(function (circle) {
console.log(circle);
circle.addEventListener('click', onClickCircle);
});
function moveDown (circleNode) {
var text = d3.select('text');
text.transition()
.attr('opacity', 1);
svg.transition()
.attr('viewBox', svg.attr('originalViewBox'));
var circle = d3.select(circleNode);
circle.transition()
.attr('cy', circle.attr('originalCy'));
}
function moveUp (circleNode) {
var text = d3.select('text');
text.transition()
.attr('opacity', 0);
var circle = d3.select(circleNode);
circle.attr('originalCy', circle.attr('cy'));
circle.transition()
.attr('cy', 25)
.each('end', function () {
moveDown(this);
});
var diameter = 2 * circle.attr('r');
svg.attr('originalViewBox', svg.attr('viewBox'));
svg.transition()
.attr('viewBox', (circle.attr('cx') - circle.attr('r')) + ' 0 ' + diameter + ' ' + diameter);
}
function onClickCircle (event) {
moveUp(event.target);
}
});
Display the source blob
Display the rendered blob
Raw
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="100%" height="100%" viewBox="0 0 300 300">
<script xlink:href="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script xlink:href="circles.js"></script>
<circle cx="25" cy="100" r="25" style="stroke: none; fill: red;"></circle>
<circle cx="100" cy="100" r="25" style="stroke: none; fill: blue;"></circle>
<text x="0" y="50">Click the circles and look surprised!</text>
</svg>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Jumping circles</title>
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="100%" height="100%" viewBox="0 0 300 300">
<script xlink:href="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script xlink:href="circles.js"></script>
<circle cx="25" cy="100" r="25" style="stroke: none; fill: red;"></circle>
<circle cx="100" cy="100" r="25" style="stroke: none; fill: blue;"></circle>
<text x="0" y="50">Click the circles and look surprised!</text>
</svg>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment