Affichage des articles dont le libellé est clock. Afficher tous les articles
Affichage des articles dont le libellé est 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 Digital Clock In Netbeans

How to Create Digital Clock in Java NetBeans

Java Digital Clock In Netbeans




In this Java Tutorial we will see How To Make a Digital Clock, With Hours, Minutes and Seconds In Netbeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.

What We Will Do In This Project:

- Create a JPanel named centerPanel with a visually appealing gradient background.
- Create a JLabel to display the current time.
Update Timer continuously using a Timer that calls the updateClock method every second.





Project Source Code:


package new_tutorials;

import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.Timer;



public class Digital_Clock extends JFrame {

    private JLabel timeLabel;
    
    public Digital_Clock(){
    
        setTitle("Digital Clock");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 200);
        setLocationRelativeTo(null);
        setResizable(false);

        
    // Create a JPanel with a background gradient    
    JPanel centerPanel = new JPanel(new GridBagLayout()){
    
        @Override
        protected void paintComponent(Graphics g){
            
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            
            // Define a gradient paint for the background
            GradientPaint gradient = new GradientPaint(new Point(0,0), new Color(37, 116, 169),
                                new Point(0,getHeight()), new Color(78, 154, 217) );
            
            g2d.setPaint(gradient);
            
            // Fill the panel with the gradient paint
            g2d.fillRect(0,0,getWidth(), getHeight());
            g2d.dispose();          
        }
    };
    add(centerPanel);
    
    timeLabel = new JLabel();
    timeLabel.setFont(new Font("Arial", Font.BOLD, 56));
    timeLabel.setHorizontalAlignment(SwingConstants.CENTER);
    timeLabel.setForeground(Color.white);
    
    
     // Add timeLabel to the center panel with padding
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.insets = new Insets(30, 30, 30, 30);  // Padding
        
        centerPanel.add(timeLabel, gbc);
        
        // Start a timer to update the clock every second
        Timer timer = new Timer(1000, e->updateClock());
        timer.start();
        
        // Initial clock update
        updateClock();
    
    }
    
    private void updateClock(){
        
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String currentTime = sdf .format(new Date());
        timeLabel.setText(currentTime);
        
    }
    
    
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(()->{});
        
           Digital_Clock dc = new Digital_Clock();
           dc.setVisible(true);
        
    }
    
    
}


The Final Result:



Java Digital Clock