An analog clock on HTML Canvas is built by drawing a circular dial and rotating three hands from the current JavaScript Date. The hour hand must include the current minutes, and the minute hand can include seconds for smoother positioning.
const now = new Date();
const seconds = now.getSeconds();
const minutes = now.getMinutes() + seconds / 60;
const hours = (now.getHours() % 12) + minutes / 60;
const secondAngle = seconds * Math.PI / 30;
const minuteAngle = minutes * Math.PI / 30;
const hourAngle = hours * Math.PI / 6;
function drawHand(angle, length, width) {
ctx.save();
ctx.translate(centerX, centerY);
ctx.rotate(angle);
ctx.moveTo(0, 12);
ctx.lineTo(0, -length);
ctx.lineWidth = width;
ctx.stroke();
ctx.restore();
}
drawClock();
setInterval(drawClock, 1000);
This replaces the old string-based setTimeout('my_function()', speed) pattern with a direct function reference.
Dial | Second hand | Minute hand | Hour hand | Clock border | Numbers | Synchronize time | Clock size | Stopwatch | JavaScript source demo
A visual clock should have a text equivalent when the current time is important. The example above updates a nearby text value alongside the Canvas.
An analog hour hand moves continuously between hour marks.
It moves the coordinate origin to the clock center and simplifies hand drawing.
They prevent each rotation from affecting later drawing operations.
For a once-per-second clock, setInterval is sufficient. Use requestAnimationFrame for smooth continuous animation.
No. JavaScript Date uses the visitor's local device time unless you explicitly supply another time source.
Canvas with JavaScript or jQuery | arc() | Canvas reference
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
14-03-2020 | |
| The java shows nothing. jquery shows canvas outline only ??? | |
01-11-2024 | |
| So cool, so retro, very wow! | |