Affichage des articles dont le libellé est Analog Clock. Afficher tous les articles
Affichage des articles dont le libellé est Analog Clock. Afficher tous les articles

JavaScript Real Time Analog Clock

How to Create an Analog with HTML, CSS and  JavaScript


How to Create an Analog with HTML, CSS and  JavaScript

In this Javascript Tutorial, we will see how to create an Analog clock with an integrated digital time display.



Project Source Code:



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Analog Clock</title>
<style>

/* Import the Poppins font from Google Fonts */
@import url(
'https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap'
);

body
{
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
font-family: 'Poppins', sans-serif;
background: linear-gradient(45deg, #16213e, #1a1a2e);
}

.clock-container{ position: relative; }

canvas
{
background: linear-gradient(45deg, #16213e, #1a1a2e);
border-radius: 50%;
box-shadow: 0 0 0 10px rgba(255,255,255,0.1),
0 0 20px rgba(0,0,0,0.3),
inset 0 0 50px rgba(0, 0, 0, 0.3);
}

.digital-time
{
position: absolute;
bottom: 20%;
left: 50%;
transform: translateX(-50%);
font-size: 1.5em;
color: #e94560;
text-transform: 0 0 10px rgba(233,69,96,0.5);
}


</style>
</head>
<body>

<div class="clock-container">

<canvas id="clock" width="400" height="400"></canvas>
<div class="digital-time" id="digital-time">00:00:00</div>

</div>

<script>
// Get the canvas element and its drawing context
const canvas = document.getElementById('clock');
const ctx = canvas.getContext('2d');
// Calculate the radius of the clock
const radius = canvas.height / 2;
// Move the origin of the canvas to the center
ctx.translate(radius, radius);

function drawClock(){

drawFace(ctx, radius);
drawNumbers(ctx, radius);
drawTime(ctx, radius);
updateDigitalTime();

}


// Function to draw the clock face
function drawFace(ctx, radius){
// Create a radial gradient for the clock face
const grad = ctx.createRadialGradient(0,0,radius * 0.95, 0, 0, radius*1.05);
grad.addColorStop(0, '#16213e'); // Inner color
grad.addColorStop(0.5, '#1a1a2e'); // Middle color
grad.addColorStop(1, '#16213e'); // Outer color

// Draw the clock face circle
ctx.beginPath();
ctx.arc(0,0,radius, 0, 2 * Math.PI);
ctx.fillStyle = grad;
ctx.fill();

// Draw the center circle
ctx.beginPath();
ctx.arc(0,0,radius * 0.1, 0, 2 * Math.PI);
ctx.fillStyle = '#e94560';
ctx.fill();

}

// Function to draw the numbers and ticks on the clock
function drawNumbers(ctx, radius){
// Set font size and alignment
ctx.font = radius * 0.15 + "px Poppins";
ctx.textBaseLine = "middle";
ctx.textAlign = "center";
ctx.fillStyle = "#fff"; // White color for numbers

// Draw numbers 1 through 12
for(let num = 1; num <= 12; num++){
let ang = num * Math.PI / 6; // Calculate angle for each number
ctx.rotate(ang); // Rotate canvas
ctx.translate(0, -radius * 0.82); // Move canvas to position
ctx.rotate(-ang); // Rotate canvas back
ctx.fillText(num.toString(), 0, 0); // Draw number
ctx.rotate(ang); // Rotate canvas back
ctx.translate(0, radius * 0.82); // Move canvas back
ctx.rotate(-ang); // Rotate canvas back
}

// Draw ticks for each minute
for(let i = 0; i < 60; i++){
let ang = i * Math.PI / 30; // Calculate angle for each tick
ctx.beginPath();
ctx.rotate(ang);

if(i % 5 === 0){
// Draw long ticks for hours
ctx.moveTo(radius * 0.9, 0);
ctx.lineTo(radius * 0.95, 0);
ctx.strokeStyle = "#e94560";
ctx.lineWidth = radius * 0.02;
}
else
{
// Draw short ticks for minutes
ctx.moveTo(radius * 0.95, 0);
ctx.lineTo(radius * 0.97, 0);
ctx.strokeStyle = "#0f3460";
ctx.lineWidth = radius * 0.01;
}

ctx.stroke(); // Render the tick
ctx.rotate(-ang); // Rotate canvas back
}

}


// Function to draw the clock hands
function drawTime(ctx, radius){
const now = new Date(); // Get current time
let hour = now.getHours(); // Get hours
let minute = now.getMinutes(); // Get minutes
let second = now.getSeconds(); // Get seconds

hour = hour % 12; // Convert hour to 12-hour format
hour = (hour * Math.PI / 6) + (minute * Math.PI / (6 * 60))
+ (second * Math.PI / (360 * 60));
// Draw hour hand
drawHand(ctx, hour, radius * 0.5, radius * 0.07, '#fff');

minute = (minute * Math.PI / 30) + (second * Math.PI / (30 * 60));
// Draw hour minute
drawHand(ctx, minute, radius * 0.75, radius * 0.05, 'yellow');

second = (second * Math.PI / 30);
// Draw hour second
drawHand(ctx, second, radius * 0.9, radius * 0.02, '#e94560');
}


// Function to draw a clock hand
function drawHand(ctx, pos, length, width, color){
ctx.beginPath();
ctx.lineWidth = width;
ctx.lineCap = "round";
ctx.shadowColor = color; // Shadow color
ctx.shadowBlur = 10; // Shadow blur
ctx.strokeStyle = color; // Hand color
ctx.moveTo(0,0); // Start from center
ctx.rotate(pos); // Rotate canvas
ctx.lineTo(0, -length); // Draw line
ctx.stroke(); // Render the hand
ctx.rotate(-pos); // Rotate canvas back
ctx.shadowBlur = 0; // Remove shadow
}


// Function to update the digital time display
function updateDigitalTime(){
const now = new Date();
const timeString = now.toLocaleTimeString('en-us',
{hour12:true, hour:'2-digit', minute:'2-digit'});
document.getElementById('digital-time').textContent = timeString;
}


// Call drawClock every second to update the clock
setInterval(drawClock, 1000);


</script>

</body>
</html>






OUTPUT:

JavaScript Real Time Analog Clock





Python Analog Clock Using Tkinter

How to Create Analog Clock In Python Tkinter

Python Analog Clock Using Tkinter



In this Python tutorial we will create an analog clock application using the Tkinter library for the graphical user interface. 
The clock displays an animated face with hour, minute, and second hands that update every second to reflect the current time.

What We Are Gonna Use In This Project:

- Python Programming Language.
- Tkinter for GUI.
- VS Code Editor.




Project Source Code:



import tkinter as tk
from datetime import datetime
import math

class AnalogClockApp:

def __init__(self,root):
# Initialize the Tkinter window
self.root = root
self.root.title("Analog Clock")
# Create a canvas for drawing the clock
self.canvas = tk.Canvas(self.root, width=300,height=300,bg="white")
self.canvas.pack()

# Delay the initial drawing
self.root.after(100, self.draw_clock)


def draw_clock(self):

# Clear the canvas
self.canvas.delete("all")

# Get the width and height of the canvas
width = self.canvas.winfo_width()
height = self.canvas.winfo_height()

# Calculate the center coordinates of the canvas
center_x = width // 2
center_y = height // 2

# Draw clock face, numbers, and hands
clock_radius = min(width, height) // 2 - 10
self.canvas.create_oval(center_x - clock_radius,
center_y - clock_radius,
center_x + clock_radius,
center_y + clock_radius,
outline = "orange", width = 5)

# Draw clock numbers
for i in range(1, 13):
# Calculate the angle for positioning each number around the clock face
angle = math.radians(360 / 12 * (i - 3))
# Calculate the x-coordinate of the number position
# based on the clock radius and angle
num_x = center_x + int(clock_radius * 0.8 * math.cos(angle))
# Calculate the y-coordinate of the number position
# based on the clock radius and angle
num_y = center_y + int(clock_radius * 0.8 * math.sin(angle))
# Create a text element to display the number at the calculated position
self.canvas.create_text(num_x, num_y, text=str(i),
font=("Helvetica", 12, "bold"))

# Get current time
current_time = datetime.now()
# Calculate the angle for the hour hand based on the current hour
hours_angle = math.radians(360 / 12 * (current_time.hour % 12 - 3))
# Calculate the angle for the minute hand based on the current minute
minutes_angle = math.radians(360 / 60 * (current_time.minute - 15))
# Calculate the angle for the second hand based on the current second
seconds_angle = math.radians(360 / 60 * (current_time.second - 15))

# Set the length of the hour hand
hour_hand_length = clock_radius * 0.5
# Set the length of the minute hand
minute_hand_length = clock_radius * 0.7
# Set the length of the second hand
second_hand_length = clock_radius * 0.9

# Calculate the x-coordinate of the hour hand
hour_hand_x = center_x + int(hour_hand_length * math.cos(
hours_angle))
# Calculate the y-coordinate of the hour hand
hour_hand_y = center_y + int(hour_hand_length * math.sin(
hours_angle))
# Draw the hour hand
self.canvas.create_line(center_x, center_y, hour_hand_x,
hour_hand_y, fill="#333", width=6)

# Calculate the x-coordinate of the minute hand
minute_hand_x = center_x + int(minute_hand_length * math.cos(
minutes_angle))
# Calculate the y-coordinate of the minute hand
minute_hand_y = center_y + int(minute_hand_length * math.sin(
minutes_angle))
# Draw the minute hand
self.canvas.create_line(center_x, center_y, minute_hand_x,
minute_hand_y, fill="#3498db", width=4)

# Calculate the x-coordinate of the second hand
second_hand_x = center_x + int(second_hand_length * math.cos(
seconds_angle))
# Calculate the y-coordinate of the second hand
second_hand_y = center_y + int(second_hand_length * math.sin(
seconds_angle))
# Draw the second hand
self.canvas.create_line(center_x, center_y, second_hand_x,
second_hand_y, fill="#e74c32", width=2)

# Update the clock every second
# Schedule the draw_clock method to be called after 1000 milliseconds
self.root.after(1000, self.draw_clock)



if __name__ == "__main__":
root = tk.Tk()
app = AnalogClockApp(root)
root.mainloop()



The Final Result:

Analog Clock Using Python Tkinter












Java Real Time Analog Clock Form In Netbeans

How to Create Analog Clock Form in Java NetBeans

Java Real Time Analog Clock In Netbeans


In this Java Long Tutorial we will go step by step on How To Design an Analog Clock  Form, With Hour Numbers and Clock Hands Using Graphics In Netbeans. we wil use a Timer to make the clock update every second.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.

What We Will Do In This Project:


- Create a AnalogClockApp class that extends JFrame for the main application window.
- Create a ClockPanel inner class within AnalogClockApp to handle clock drawing.
- Make a Timer to update the clock time.
- Calculate clock dimensions, center coordinates, and draw the clock face.
- Check the current time, extract hours, minutes, and seconds.
- Calculate rotation angles for clock hands based on the time.
- Draw clock hands using drawClockHand method with different colors and thicknesses.




Project Source Code:


package analogclockapp;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

/**
 *
 * @author 1BestCsharp
 */
public class AnalogClockApp extends JFrame {
    
    public AnalogClockApp()
    {
        setTitle("Analog Clock");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 400);
        setLocationRelativeTo(null);
        ClockPanel clock = new ClockPanel();
        add(clock);
        
        // Start a timer to update the clock every second
        Timer timer = new Timer(1000, e->{
        
            clock.setCurrentTime();
            clock.repaint();
            
        });
        timer.start();
        
        // Initial clock update
        clock.setCurrentTime();
        
    }
    
    
    // Create an Inner class representing the clock panel
    private class ClockPanel extends JPanel
    {
        private int centerX;
        private int centerY;
        private int clockRadius;
        
        public ClockPanel()
        {
            setBackground(Color.white);
        }
        
        public void setCurrentTime()
        {
            // Repaint the clock panel to update the clock hands
            repaint();
        }
        
        
        @Override
        protected void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            
            // Calculate clock dimensions and center
            clockRadius = Math.min(getWidth(), getHeight()) / 2 - 20; // Calculate the radius of the clock, leaving a margin of 20 pixels
            centerX = getWidth() / 2; // Calculate the X-coordinate of the clock center
            centerY = getHeight() / 2; // Calculate the Y-coordinate of the clock center
            
            // Draw clock face (circle)
            g2d.setColor(new Color(50,50,50)); // Set the color for the clock face
             // Draw a filled circle representing the clock
            g2d.fillOval(centerX - clockRadius, centerY - clockRadius, 2 * clockRadius, 2 * clockRadius);
            
            // Draw hour numbers
            g2d.setFont(new Font("Arial", Font.BOLD, 14)); // Set the font for drawing hour numbers
            g2d.setColor(Color.white); // Set the color for the hour numbers
            
            for(int hour = 1; hour <= 12; hour++)
            {
                double angle = Math.toRadians(90-(360/12) * hour); // Calculate the angle for placing the hour number
                int x = (int)(centerX + clockRadius * 0.8 * Math.cos(angle)); // Calculate the X-coordinate of the hour number position
                int y = (int)(centerY - clockRadius * 0.8 * Math.sin(angle)); // Calculate the Y-coordinate of the hour number position
                g2d.drawString(Integer.toString(hour), x - 7, y + 5); // Draw the hour number with an offset
            }
            
            // Get current time
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); // Create a date formatter for hours, minutes, and seconds
            String currentTime = sdf.format(new Date()); // Get the current time as a formatted string
            
            // Extract hours, minutes, and seconds
            int hours = Integer.parseInt(currentTime.substring(0,2)); // Extract the hours
            int minutes = Integer.parseInt(currentTime.substring(3,5)); // Extract the minutes
            int seconds = Integer.parseInt(currentTime.substring(6,8)); // Extract the seconds
            
            // Calculate rotation angles for clock hands
            double hoursAngle = Math.toRadians(90 - (360 / 12) * hours); // Calculate the angle for the hour hand
            double minutesAngle = Math.toRadians(90 - (360 / 60) * minutes); // Calculate the angle for the minutes hand
            double secondsAngle = Math.toRadians(90 - (360 / 60) * seconds); // Calculate the angle for the seconds hand
            
            // Draw clock hands
            // Draw the hour hand in yellow
            drawClockHand(g2d, centerX, centerY, clockRadius * 0.5, hoursAngle, 6, Color.yellow);
            
            // Draw the minute hand in yellow
            drawClockHand(g2d, centerX, centerY, clockRadius * 0.7, minutesAngle, 4, Color.yellow);
            
            // Draw the second hand in red
            //g2d.setColor(new Color(255, 90, 90));
            drawClockHand(g2d, centerX, centerY, clockRadius * 0.8, secondsAngle, 2, new Color(255, 90, 90));

        }
        
        
        
        private void drawClockHand(Graphics2D g2d, int x, int y, double length, 
                                   double angle, int thickness, Color color)
        {
            // Set the stroke thickness and color for drawing the clock hand
            g2d.setStroke(new BasicStroke(thickness));
            g2d.setColor(color);
            int x2 = (int)(x + length * Math.cos(angle));
            int y2 = (int)(y - length * Math.sin(angle));
            // Draw the clock hand from the center to the calculated position
            g2d.drawLine(x, y, x2, y2);
        }
        
        
    }


    
    
    
    public static void main(String[] args) {
        
        SwingUtilities.invokeLater(()->{
        
            AnalogClockApp app = new AnalogClockApp();
            app.setVisible(true);
            
        });
        
    }

}



The Final Result:

Java Analog Clock

Java Analog Clock Form

Java Real Time Analog Clock In Netbeans


download the source code