Skip to content

Instantly share code, notes, and snippets.

@RGamberini
Last active August 29, 2015 14:14
Show Gist options
  • Save RGamberini/2ec63bac48a937c2957a to your computer and use it in GitHub Desktop.
Save RGamberini/2ec63bac48a937c2957a to your computer and use it in GitHub Desktop.
Circle Animation
<html>
<head>
</head>
<body>
<form>
Stroke: <input type="checkbox" id="stroke">
</form>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
function HueCircle(scale, quantity) {
this.scale = scale;
this.radianscale = d3.scale.linear()
.domain([0, quantity])
.range([0, 2 * Math.PI]);
this.huescale = d3.scale.linear()
.domain([0, quantity])
.range([0, 720]);
this.circle_x = function(i, delta, scale) {
return Math.sin(this.radianscale(i) + delta) * this.scale;
};
this.circle_y = function(i, delta, scale) {
return Math.cos(this.radianscale(i) + delta) * this.scale;
};
return this;
}
d3.selection.prototype.moveToFront = function() {
return this.each(function(){
this.parentNode.appendChild(this);
});
};
var height = 500, width = 900, scale = 168, size = 64, stroke = false,
svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + (height / 2) + ")");
d3.select("#stroke").on("change", function() {
console.log(this.value + " " + stroke);
stroke = !stroke;
})
function distance(x, y, _x, _y) {
return Math.sqrt(Math.pow(x + _x, 2) + Math.pow(y + _y,2));
}
function update(size, circle, delta, stroke) {
var circles = svg.selectAll("circle")
.data(d3.range(size), function(d) { return d; });
circles.enter().append("circle")
.attr("r", circle.size)
.attr("stroke", stroke ? "" : "black")
.attr("stroke-width", stroke ? 0 : 4)
.style("fill", function (d,i) {
return d3.hsl(circle.huescale(i) % 360, 0.75, 0.5);
});
d3.select(circles[0][i]).moveToFront();
circles.attr("cx", function (d, i) { return circle.circle_x(i, delta) + (190 * Math.sin(circle.radianscale(d))); })
.attr("cy", function(d, i) { return circle.circle_y(i, delta);})
.attr("stroke", stroke ? "black" : "")
.attr("stroke-width", stroke ? 4 : 0);
circles.exit().remove();
}
// How far the circle is in radians
var delta = 0, huecircle = HueCircle(168, size), i = 0, range = d3.range(0, size / 2).concat(d3.range(size / 2, 0, -1));
update(128, huecircle, 0);
//MAIN LOOP START
setInterval(
function() {
delta -= 0.0125;
update(128, huecircle, delta, stroke);
i +=1;
if (i == size) {
i = 0;
}
if (delta == Math.PI * 2) {
delta = 0;
}
}, 50);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment