This is a vibrant and interactive clock application created using JavaScript and HTML5 Canvas! Here's how I brought it to life ⭐✨.
- 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. Fetching User Timezone via IP 🌐
- 12. Project Completion Date
- 13. License
I set the canvas dimensions in the HTML, allowing flexibility to adjust the width and height to meet specific design needs.
The canvas origin is at the top-left corner (0, 0), and coordinates increase as you move right (X-axis) and down (Y-axis). This forms the base of our clock design.
To visualize the grid, I created a function that draws horizontal and vertical axes, emphasizing the center with red lines.
To draw the clock face, I parameterized a circle using its radius and center coordinates. By iterating over different angles (θ), I constructed the circle smoothly. 🔬
To mark hours and minutes, I used a function to add "tics" at calculated angles. Longer tics represent hours, while shorter ones denote minutes.
I displayed the current datetime using JavaScript's Date
object and updated it dynamically in the paragraph below the clock.
let d = new Date();
document.getElementById("some_id").innerHTML = d;
I calculated angles for hour, minute, and second hands based on the current time. Using these angles, I drew hands radiating from the clock center.
To ensure the clock updated in real-time, I used setInterval
to refresh the drawing every second. This added a smooth and consistent animation. ✨
Before redrawing the clock for each frame, I cleared the canvas using:
graphics.clearRect(0, 0, canvas.width, canvas.height);
This avoided overlaps and ensured clean rendering.
By calculating fractional angles for seconds and minutes, I made the clock hands move smoothly instead of jumping between ticks. This added realism.
To customize the clock to the user's timezone, I integrated the ipapi.co
API. Here's how:
- I fetched the user's timezone using their IP address.
- I used the detected timezone to adjust the time displayed by the clock.
- If timezone detection failed, I defaulted to the local time offset.
-
**fetchTimeZone()**
:- Queries the API and extracts the timezone.
- Adjusts the time offset accordingly.
-
**updateDateTime()**
:- Updates the displayed time every second using the fetched timezone.
async function fetchTimeZone() {
const response = await fetch('https://ipapi.co/json/');
const data = await response.json();
console.log(data.timezone);
}
This integration ensures a personalized experience for users worldwide! ✨⌚
This project was completed on Sunday, 13 August 2023, at 5:20 PM.
This project is licensed under the MIT License.