Created
December 10, 2012 21:22
-
-
Save olizilla/4253531 to your computer and use it in GitHub Desktop.
D3 Sine Worm
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
<html> | |
<head> | |
<meta charset="utf-8"> | |
<script src="http://d3js.org/d3.v2.js"></script> | |
<style> | |
body{ | |
margin:0; | |
background: #222; | |
} | |
.controls{ | |
text-align: center; | |
} | |
</style> | |
</head> | |
<body> | |
<svg id='' width="100%" height="300"></svg> | |
<div class="controls"> | |
<input id="c" type="range" value="100" min='50' max="250" step="1"> | |
</div> | |
<script> | |
var svg = d3.select('svg'); | |
function dots(data){ | |
// Data: Join the data & it's representation | |
var dots = svg.selectAll('circle').data(data, function(d){return d.id}); | |
// Enter: The set of new data points without an existing representation | |
dots.enter() | |
.append('circle') | |
// Update: update all points with both data and representation. The circles created during the enter() step above are also updated. | |
dots | |
.transition() | |
.attr("cx", function(d) { return d.x } ) | |
.attr("cy", function(d) { return d.y } ) | |
.attr("r", function(d) { return d.r } ) | |
.attr('fill', function(d) { return d.fill }); | |
// Exit: the set of representations without a data | |
dots.exit() | |
.transition() | |
.attr("fill", '#FFFFFF').attr('r', 0) | |
.remove(); | |
} | |
function val(id){ | |
var node = document.getElementById(id); | |
return parseInt(node.value); | |
} | |
function makeData(a, b, color){ | |
return { | |
id: a, | |
x: (8 * a) % window.innerWidth, | |
y: 150 + (Math.sin(b/10) * 100), | |
r: (( val('c') ) * Math.random()) / 5, | |
fill: color | |
} | |
} | |
var count = 0; | |
var data = []; | |
var maxDots = 20; | |
var color = d3.rgb('#911'); | |
function loop() { | |
var fill = color.darker((count % maxDots) * Math.random() / 5); | |
var circleData = makeData(count, count, fill.toString()); | |
if(data.length < maxDots){ | |
data.push(circleData); | |
} else { | |
var index = (maxDots-1) - (count % maxDots); | |
var oldDot = data[index]; | |
circleData.id = oldDot.id; | |
data[index] = circleData; | |
} | |
dots(data); | |
count++; | |
setTimeout(loop, val('c')) | |
} | |
loop() | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment