Skip to content

Instantly share code, notes, and snippets.

@kosamari
Created October 13, 2014 23:47
Show Gist options
  • Save kosamari/90cc3862ea68957e19de to your computer and use it in GitHub Desktop.
Save kosamari/90cc3862ea68957e19de to your computer and use it in GitHub Desktop.
D3 Line clock
<!DOCTYPE html>
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js"></script>
<style type="text/css">
rect.overlay {
fill: #2279bd;
}
rect.base{
fill: #f3f3f3;
}
</style>
</head>
<body>
<script type="text/javascript">
var w = 960, //1920
h = w*0.5625, // 16:9 aspect ratio
lh = w/50, //line height
y = d3.scale.ordinal().domain(d3.range(11)).rangePoints([0, h], 0),
r = 2 * Math.PI
var fields = [
{name: "hours", value: 0, size: 12},
{name: "minutes", value: 0, size: 60},
{name: "seconds", value: 0, size: 60}
];
var arc = d3.svg.arc()
.innerRadius(w/12)
.outerRadius(w/12*1.15)
.startAngle(0)
.endAngle(function(d) {
return (d.value / d.size) * r;
});
var svg = d3.select("body").append("svg")
.attr("width", w)
.attr("height", h)
.append("g");
var base = svg.selectAll(".base")
.data(fields);
base.enter().append("rect")
.attr("transform", function(d,i){return "translate( 0," + (y(i+4)-(lh/2)) + ")"})
.attr("class",'base')
.attr("width",w)
.attr("height", lh)
setInterval(function() {
var now = new Date();
fields[0].previous = fields[0].value; fields[0].value = changeto12(now.getHours());
fields[1].previous = fields[1].value; fields[1].value = now.getMinutes();
fields[2].previous = fields[2].value; fields[2].value = now.getSeconds();
var path = svg.selectAll(".overlay")
.data(fields);
path.enter().append("rect")
.attr("transform", function(d,i){return "translate( 0," + (y(i+4)-(lh/2)) + ")"})
.attr("class",'overlay')
.attr("width",0)
.attr("height", lh)
.transition()
.duration(1000)
.attr("width", function(d,i){return w*(d.value/d.size)})
path.transition()
.duration(1000)
.attr("width", function(d,i){
if(d.value === 0) {d.value = d.size}
return w*(d.value/d.size)
});
}, 1000);
function changeto12(num){
if(num>12){return num-12;}
return num
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment