This is a simple clock created using JavaScript and HTML5 Canvas. Steps 1 to 10 show how the clock wwas made.
- JavaScript Canvas Clock
- Languages used
- Table of Contents
- 1. Canvas Dimensions
- 2. Origin and Coordinates
- 3. Drawing Axes
- 4. Drawing a Circle
- 5. Adding Clock Tics
- 6. Displaying Current Datetime
- 7. Creating Clock Hands
- 8. Using setInterval
- 9. Clearing the Canvas
- 10. Smooth Clock Movement
- 11. Project Completion Date
- 12. License
The canvas dimensions are specified in your code. You can adjust the width and height to fit your requirements.
The origin of the canvas is typically at the top-left corner (0, 0). Coordinates increase as you move right (X-axis) and down (Y-axis).
You can create a function to draw axes to help with your design.
A circle can be drawn by generating points along its circumference and creating a path from one point to the next. Parameterise a circle with radius, r, and centre, c, as follows:
Then create a function that draws a circle of radius 240 centered in the middle of the canvas. Draw the circle by generating points by sweeping over different values of θ ∈ [0, 2π] and creating a path from p(θi) to p(θi+1). Close and then stroke the path. See how the circle becomes smoother as you increase the number of points.
To represent hours and minutes on the clock, you can create a function that draws lines from the center to different radii.
You can use a JavaScript date object to display the current datetime.
let d = new Date();
document.getElementById("some_id").innerHTML = d;
Functions convert the current time into θ values for each clock hand and draw the lines.
The setInterval
function is used to update the clock every second.
The canvas should be cleared before each render. Use the following code to clear the canvas:
graphics.clearRect(0, 0, canvas.width, canvas.height);
Adjust the code to make the clock hands move smoothly, and update the second hand every 10ms. Remove the axes/guidelines.
This project was completed on Sunday, 13 August 2023, at 5:20 PM.
This project is licensed under the MIT License.