/
clock.html
94 lines (73 loc) · 2.23 KB
/
clock.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<!DOCTYPE html>
<html>
<head>
<title>Analog Clock</title>
<style>
#clock {
padding: 10px;
background-image: url("images/clockbgnewlarge.jpg");
background-size:220px 225px;
background-repeat:no-repeat;
}
</style>
</head>
<body>
<div id="current-time">12:00:00 AM</div>
<canvas id="clock" width="200" height="205">
If you can see this message, your browser does not support canvas
and needs an update. Sorry. :(
</canvas>
<script>
document.addEventListener('DOMContentLoaded', displayTime);
function displayTime() {
var h = 10;
var m = 30;
var s = 0;
var timeString = formatHour(h) + ":" + padZero(m) + ":" + padZero(s) + " " + getTimePeriod(h);
document.querySelector("#current-time").innerHTML = timeString;
// --- Analog clock ---//
var canvas = document.querySelector("#clock");
var context = canvas.getContext("2d");
// You can change this to make the clock as big or small as you want.
// Just remember to adjust the canvas size if necessary.
var clockRadius = 100;
// Make sure the clock is centered in the canvas
var clockX = canvas.width / 2;
var clockY = canvas.height / 2;
// Make sure TAU is defined (it's not by default)
Math.TAU = 2 * Math.PI;
function drawArm(progress, armThickness, armLength, armColor) {
var armRadians = (Math.TAU * progress) - (Math.TAU/4);
var targetX = clockX + Math.cos(armRadians) * (armLength * clockRadius);
var targetY = clockY + Math.sin(armRadians) * (armLength * clockRadius);
context.lineWidth = armThickness;
context.strokeStyle = armColor;
context.beginPath();
context.moveTo(clockX, clockY); // Start at the center
context.lineTo(targetX, targetY); // Draw a line outwards
context.stroke();
}
drawArm(h / 12, 10, 0.50, 'black'); // Hour
drawArm(m / 60, 4, 0.75, 'black'); // Minute
}
function padZero(num) {
if (num < 10) {
return "0" + String(num);
}
else {
return String(num);
}
}
function formatHour(h) {
var hour = h % 12;
if (hour == 0) {
hour = 12;
}
return String(hour)
}
function getTimePeriod(h) {
return (h < 12) ? "AM" : "PM";
}
</script>
</body>
</html>