Analog Clock

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 3

<!

DOCTYPE html>
<html>

<head>
<title>Analog Clock</title>

<style>
#current-time {
display: block;
font-weight: bold;
text-align: center;
width: 200px;
padding: 10px;
}
#clock {
padding: 10px;
border:1px solid #000000;
}
</style>
</head>

<body>
<canvas id="clock" width="200" height="200">
If you can see this message, your browser does not support canvas
and needs an upate. Sorry. :(
</canvas>


<script>
document.addEventListener('DOMContentLoaded', startTimer);
function startTimer()
{
setInterval(updateClocks, 1000);
}
function updateClocks()
{
var now = new Date();
var h = now.getHours() % 12;
var m = now.getMinutes();
var s = now.getSeconds();
// --- Analog clock ---//
var canvas = document.getElementById("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;
context.clearRect(0, 0, canvas.width, canvas.height);
// Draw background
for (var i = 0; i < 12; i++)
{
var innerDist = (i % 3) ? 0.75 : 0.7;
var outerDist = (i % 3) ? 0.95 : 1.0;
context.lineWidth = (i % 3) ? 4 : 10;
context.strokeStyle = '#999999';
var armRadians = (Math.TAU * (i/12)) - (Math.TAU/4);
var x1 = clockX + Math.cos(armRadians) * (innerDist * clockRadiu
s);
var y1 = clockY + Math.sin(armRadians) * (innerDist * clockRadiu
s);
var x2 = clockX + Math.cos(armRadians) * (outerDist * clockRadiu
s);
var y2 = clockY + Math.sin(armRadians) * (outerDist * clockRadiu
s);
context.beginPath();
context.moveTo(x1, y1); // Start at the center
context.lineTo(x2, y2); // Draw a line outwards
context.stroke();
}
// Draw arms
function drawArm(progress, armThickness, armLength, armColor)
{
var armRadians = (Math.TAU * progress) - (Math.TAU/4);
var targetX = clockX + Math.cos(armRadians) * (armLength * clock
Radius);
var targetY = clockY + Math.sin(armRadians) * (armLength * clock
Radius);
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();
}
var hProgress = (h/12) + (1/12)*(m/60) + (1/12)*(1/60)*(s/60);
var mProgress = (m/60) + (1/60)*(s/60);
var sProgress = (s/60);
drawArm( hProgress, 10, 1/2, '#000000'); // Hour
drawArm( hProgress, 10, -5/clockRadius, '#000000'); // Hour
drawArm( mProgress, 4, 3/4, '#000000'); // Minute
drawArm( mProgress, 4, -2/clockRadius, '#000000'); // Minute
drawArm( sProgress, 2, 1, '#FF0000'); // Second
drawArm( sProgress, 2, -10/clockRadius, '#FF0000'); // Second
}
</script>
</body>
</html>

You might also like