Skip to content

Instantly share code, notes, and snippets.

@easadler
Last active November 7, 2016 20:50
Show Gist options
  • Save easadler/519e62439218884afeacaa44c768c12b to your computer and use it in GitHub Desktop.
Save easadler/519e62439218884afeacaa44c768c12b to your computer and use it in GitHub Desktop.
D3 Rave Part 2
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
// Feel free to change or delete any of the code you see in this editor!
var width = 960,
height = 500,
radius = 30;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height).style('background-color', 'black')
var xValues = d3.range(-18*radius,width + 18*radius, 3*radius)
var yValues = d3.range(-18*radius,height + 18*radius, 3*radius)
var data = []
for(var x =0; x< xValues.length; x++){
for(var y = 0; y < yValues.length; y++){
data.push({x: xValues[x],y: yValues[y], i: x, j: y})
}
}
var circle = svg.append('g').selectAll('circle').data(data)
.enter().append("circle")
.attr("cy", function(d){ return d.y;})
.attr("cx", function(d){ return d.x;})
.attr('r', 10)
.attr('fill', function(d){if((d.i + d.j) % 2 == 0){ return 'red'} else {
return 'blue'
}})
var w = width,
h = height;
var times = 0
d3.interval(function(elapsed) {
var m = 6*radius;
circle.transition().duration(100).ease(d3.easeBounce).attr("cx", function(d) {
if(((d.i + d.j) % 2 == 0 && (times % 4 == 0 || times % 4 == 1)) || ((d.i + d.j) % 2 == 1 && (times % 4 == 2 || times % 4 == 3))){
d.x += m
} else {
d.x -= m;
}
return d.x
})
.attr("cy", function(d) {
if(((d.i + d.j) % 2 == 0 && (times % 4 == 1 || times % 4 == 2)) ||((d.i + d.j) % 2 == 1 && (times % 4 == 0 || times % 4 == 3)) ){
d.y += m;
}
else{
d.y -= m;
}
return d.y
})
.attr('fill', function(d){
if((d.i + d.j) % 2 == 0 && times % 2 == 0){
return 'blue'
}
else if((d.i + d.j) % 2 == 0) {
return 'red'
}
if((d.i + d.j) % 2 != 0 && times % 2 == 0){
return 'red' }
else{
return 'blue'
}
})
.attrTween('r', function(){
return function(t){
return (radius - .8 * radius)*4*(t - 0.5)**2 + .8 * radius;
};
})
times++;
}, 100);
var times2 = 0;
d3.interval(function(){
d3.select('svg').transition().duration(5).style('background-color',function(){ if(times2 % 2 == 0){ return 'white'} else {return 'black'}});
times2++;
}, 5)
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment