Simple analog clock.
Last active
January 4, 2025 03:38
-
-
Save gongzhitaao/a09b72a9b72a3618f544 to your computer and use it in GitHub Desktop.
Analog Clock
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<meta charset="utf-8"> | |
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> | |
<style> | |
svg { | |
shape-rendering: geometricPrecision; | |
} | |
.frame { | |
fill: none; | |
stroke: #ddd; | |
stroke-width: 2px; | |
} | |
.center { | |
stroke: none; | |
fill: red; | |
} | |
.hand { | |
stroke: #111; | |
} | |
.hour { | |
stroke-width: 10px; | |
} | |
.minute { | |
stroke-width: 5px; | |
} | |
.second { | |
stroke: red; | |
stroke-width: 2px; | |
} | |
</style> | |
<body> | |
<script> | |
var width = 960; | |
var height = 500; | |
var cx = width / 2.; | |
var cy = height / 2.; | |
var length = [100, 140, 180]; | |
var svg = d3.select("body") | |
.append("svg") | |
.attr("width", width) | |
.attr("height", height); | |
var data = [ | |
{name: "hour", x1: cx, y1: cy, x2: 0, y2: 0}, | |
{name: "minute", x1: cx, y1: cy, x2: 0, y2: 0}, | |
{name: "second", x1: cx, y1: cy, x2: 0, y2: 0}, | |
]; | |
(function tick() { | |
var date = new Date(); | |
var h = date.getHours() % 12; | |
var m = date.getMinutes(); | |
var s = date.getSeconds(); | |
var angles = [0, 0, s * Math.PI / 30.]; | |
angles[1] = m * Math.PI / 30. + angles[2] / 60.; | |
angles[0] = h * Math.PI / 6 + angles[1] / 12.; | |
for (var i = 0; i < 3; ++i) { | |
data[i].x2 = length[i] * Math.sin(angles[i]) + cx; | |
data[i].y2 = -length[i] * Math.cos(angles[i]) + cy; | |
} | |
var hands = svg.selectAll("line") | |
.data(data, function(d) { return d.name; }); | |
hands.enter().append("line") | |
.attr("class", function(d) { return "hand " + d.name; }) | |
.attr("stroke-linecap", "round") | |
.attr("x1", function(d) { return d.x1; }) | |
.attr("y1", function(d) { return d.y1; }) | |
hands | |
.attr("x2", function(d) { return d.x2; }) | |
.attr("y2", function(d) { return d.y2; }) | |
setTimeout(tick, 1000); | |
})(); | |
svg.selectAll("circle") | |
.data([{name: "frame", r: 200}, | |
{name: "center", r: 10}], | |
function(d) { return d.name; }) | |
.enter().append("circle") | |
.attr("class", function(d) { return d.name; }) | |
.attr("r", function(d) { return d.r; }) | |
.attr("cx", cx) | |
.attr("cy", cy); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment