Fast prototyping of apps using Sketch and d3.js, please refer to the the explanatory post.
Last active
August 29, 2015 14:00
-
-
Save maelp/11522092 to your computer and use it in GitHub Desktop.
Fast prototyping tricks - Sorting elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<style> | |
body { | |
width: 960px; | |
padding-top: 40px; | |
margin: auto; | |
position: relative; | |
} | |
svg { | |
width: 100%; | |
max-height: 400px; | |
font-family: sans-serif; | |
} | |
</style> | |
<svg width='400px' height='100px' viewBox='0 0 500 100' style='fill:#f48'> | |
<g id='group-unsorted' transform='translate(25, 50)'> | |
<circle cx='0' cy='0' r='10'></circle> | |
<circle cx='100' cy='0' r='10'></circle> | |
<circle cx='50' cy='0' r='10'></circle> | |
<circle cx='150' cy='0' r='10'></circle> | |
<text x='75' y='50' style='fill:#444;text-anchor:middle'>Without sort</text> | |
</g> | |
<g id='group-sorted' transform='translate(275, 50)'> | |
<circle cx='0' cy='0' r='10'></circle> | |
<circle cx='100' cy='0' r='10'></circle> | |
<circle cx='50' cy='0' r='10'></circle> | |
<circle cx='150' cy='0' r='10'></circle> | |
<text x='75' y='50' style='fill:#444;text-anchor:middle'>With sort</text> | |
</g> | |
</svg> | |
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> | |
<script type='text/javascript'> | |
function animateGrowingCircle(maxRadius, minRadius) { | |
var animateFunction = function () { | |
d3.select(this) | |
.attr('r', minRadius) | |
.transition() | |
.duration(1000) | |
.attr('r', maxRadius) | |
.transition() | |
.duration(1000) | |
.attr('r', minRadius) | |
.each('end', function () { | |
d3.select(this).each(animateFunction); | |
}); | |
}; | |
return animateFunction; | |
} | |
window.addEventListener('load', function () { | |
svg = d3.select('svg'); | |
svg.select('#group-unsorted').selectAll('circle') | |
.each(function (d, i) { | |
d3.select(this) | |
.transition() | |
.delay(i*250) | |
.each(animateGrowingCircle(10, 20)); | |
}); | |
svg.select('#group-sorted').selectAll('circle') | |
.datum(function () { | |
return {'x': +d3.select(this).attr('cx')}; | |
}) | |
.sort(function (a, b) { return a.x - b.x; }) | |
.each(function (d, i) { | |
d3.select(this) | |
.transition() | |
.delay(i*250) | |
.each(animateGrowingCircle(10, 20)); | |
}); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment