Skip to content

Instantly share code, notes, and snippets.

@pvernier
Last active March 11, 2018 19:26
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 pvernier/a56a5d9e49736a803370625abe5f9070 to your computer and use it in GitHub Desktop.
Save pvernier/a56a5d9e49736a803370625abe5f9070 to your computer and use it in GitHub Desktop.
D3 clock
license: gpl-3.0

A clock made using SVG circle and d3-timer.

The current hour is represented in red, the current minute in orange and the second in yellow.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
svg {
background-color: #bdbdbd;
width: 500px;
height: 500px;
}
circle {
fill: #f0f0f0;
}
.second {
fill: #fecc5c;
}
.minute {
fill: #fd8d3c;
}
.hour {
fill: #bd0026;
}
</style>
</head>
<body>
<svg></svg>
</body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-timer.v1.min.js"></script>
<script type="text/javascript">
var svg = d3.select("svg")
// Create the clock
var items = 60;
var x0 = 250;
var y0 = 250;
var r = 240
for(var i = 0; i < items; i++) {
var x = x0 + r * Math.cos(2 * Math.PI * i / items);
var y = y0 + r * Math.sin(2 * Math.PI * i / items);
if (i < 45) {
var id = i + 15
} else {
var id = i % 45
}
var circle = svg.append("circle")
.attr("cx", x)
.attr("cy", y)
.attr("id", "c_" + id)
if (i % 5 == 0) {
circle.attr("r", 5)
} else {
circle.attr("r", 3)
}
}
var t = d3.interval(function(elapsed) {
// Clear the previous second, minute, hour
d3.select("circle.second")
.classed("second", false)
d3.select("circle.minute")
.classed("minute", false)
d3.select("circle.hour")
.classed("hour", false)
// Check the current time
var current_time = new Date()
// Display the current second, minute, hour
d3.select("circle#c_" + current_time.getSeconds())
.classed("second", true)
d3.select("circle#c_" + current_time.getMinutes())
.classed("minute", true)
d3.select("circle#c_" + current_time.getHours() %12 * 5)
.classed("hour", true)
}, 1000); // Every second
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment