Skip to content

Instantly share code, notes, and snippets.

@mikehadlow
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikehadlow/0c7e9540da1208de6d9f to your computer and use it in GitHub Desktop.
Save mikehadlow/0c7e9540da1208de6d9f to your computer and use it in GitHub Desktop.
Segment Clock

A little D3js demo of a clock based on circle segments, more normally used for creating pie charts. I've speeded up time to 1 second == 1 hour to make it a little more visually interesting.

<!DOCTYPE html>
<html xmlns:xlink="http://www.w3.org/1999/xlink">
<head>
</head>
<body>
</body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var height = 800;
var width = height;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var segmentCircle = function(g, n, id, cx, cy, innerRadius, outerRadius) {
var gInner = g.append('g')
.attr('transform', 'translate(' + cx + ', ' + cy + ')');
var pi = Math.PI;
var pi12 = 2 * pi / n;
var margin = pi / 180;
var segs = [];
for(var i=0; i<n; i++) {
segs.push([i*pi12 + margin, (i+1)*pi12 - margin]);
}
var arcs = gInner.selectAll('path').data(segs).enter().append('path')
.attr('id', function(d,i) { return id + '-' + i; });
var arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius)
.startAngle(function(d) { return d[0]; })
.endAngle(function(d) { return d[1]; });
arcs.attr('d', arc)
.style('fill', 'none')
.style('stroke', 'black')
.style('stroke-width', 0.5);
return gInner;
}
var mins = segmentCircle(svg, 60, 'min', 250, 250, 180, 200);
var hours = segmentCircle(svg, 12, 'hour', 250, 250, 140, 160);
var min = 0, oldMin = 59;
var hour = 0, oldHour = 11;
var interval = function() {
mins.select('#min-' + min).style('fill', 'red');
mins.select('#min-' + oldMin).style('fill', 'none');
oldMin = min;
min++;
if(min == 60) {
min = 0;
if(hour == 0) {
hours.selectAll('path').style('fill', 'none');
}
hours.select('#hour-' + hour).style('fill', 'lightblue');
//hours.select('#hour-' + oldHour).style('fill', 'none');
oldHour = hour;
hour++;
if(hour == 12) {
hour = 0;
}
}
}
setInterval(interval, 1000 / 60);
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment