search
HomeWeb Front-endJS TutorialHow to create an analog clock using HTML, CSS and JavaScript?

如何使用 HTML、CSS 和 JavaScript 创建模拟时钟?

In this tutorial we will design an analog clock with the help of HTML and CSS and use JavaScript Its working, this will display the current time in hours, minutes and seconds format.

Approach
  • We will use the Date object and With some calculations, we will display hours, minutes, and seconds.

  • We will get the system time from a JavaScript object Date() which has functions such as >getHours(), getSecond() and getMinutes().

  • After getting we will apply the hours , minutes and seconds formats to convert all three-hand hours, minutes and seconds of rotation.

The analog clock displays time through three hands that move continuously and mark the time from 1 to 12 as it is displayed.

HTML

Create an HTML file named index.html and add some boilerplate code, this is the basic html syntax as shown below, inside our HTML code there is a div named "sizeOfAnalog", has the same class name "sizeOfAnalog" inside these three divs, with names hour_clock, minutes_clock, seconds_clock.

CSS

We will add inner CSS as well as inner JavaScript in the HTML code. Use the tag to apply internal CSS and <script></script> to apply internal JavaScript.

JavaScript

In the JavaScript part, we do the main logic work. We will use the JavaScript Date() object and its functions getHours(), getSecond(), and getMinutes() to get the current time in hours, minutes, and seconds. Once we have the hours, minutes, and seconds format, we will apply the rotation that converts all three hands of the hours, minutes, and seconds.

Steps

Step 1 - We use the "background: url(clock.png) no-repeat;"code to apply the clock on the screen The background image, the no-repeat here is to prevent the image from repeating itself.

Step 2 - Now we will get the current time using Date() object and we can also get the current hour, minutes and seconds respectively from the Date object. Now we will get the hours, minutes and seconds from the HTML code and convert the rotation of the hand to 360 degrees.

Step 3 - As we know, degrees after 360 degrees will be considered as one rotation. So if you want to get a total of 12 hours from these 360 ​​degrees, you can do it using (360/12), which will give you 30 degrees in one hour.

Step 4 - Same per minute as we need a total of 360 minutes for 60 minutes so this can be done using the required (360/60) = 6 degrees per minute.

Step 5 - In the JavaScript part using setInterval() we can run the set clock every 1000ms (milliseconds) since 1 second equals 1000ms.

Therefore, we use new to create a date object Date()

Get the hours between 0 and 23getHours()

Get the minutes between 0 and 59getMinutes()

Get the seconds between 0 and 59getSeconds()

Step 6 - Once we have all three values, we will rotate each hand and our analog clock will start showing the time.

Example (Full Program)

Below is the complete code to create an analog clock using HTML, CSS and JavaScript.

<!DOCTYPE html>
<html>
<head>
   <title>Analog Clock Tutorials Point</title>
   <style>
      #sizeOfAnalog {
         position: relative;
         background: url(https://www.tutorialspoint.com/assets/questions/tmp/clock.png) no-repeat;
         background-size: 100%;
         margin-top: 2%;
         margin: auto;
         height: 90vh;
         width: 90vh;
      }
      #hour_clock {
         position: absolute;
         background: black;
         border-radius: 10px;
         transform-origin: bottom;
         height: 25%;
         top: 25%;
         left: 48.85%;
         opacity: 0.8;
         width: 2%;
      }
      #minute_clock {
         position: absolute;
         background: black;
         border-radius: 10px;
         transform-origin: bottom;
         left: 48.9%;
         opacity: 0.8;
         width: 1.6%;
         height: 32%;
         top: 18%;
      }
      #second_clock {
         position: absolute;
         background: black;
         border-radius: 10px;
         transform-origin: bottom;
         width: 1%;
         height: 36%;
         top: 14%;
         left: 50%;
         opacity: 0.8;
      }
   </style>
</head>
<body>
   <div id="sizeOfAnalog">
   <div id="hour_clock"></div>
   <div id="minute_clock"></div>
   <div id="second_clock"></div>
   </div>
   <script>
      var hour = document.getElementById("hour_clock");
      var minute = document.getElementById("minute_clock");
      var seconds = document.getElementById("second_clock");

      var addClock = setInterval(function clock() {
         var date_now = new Date();
         var hr = date_now.getHours();
         var min = date_now.getMinutes();
         var sec = date_now.getSeconds();

         var calc_hr = hr * 30 + min / 2;
         var calc_min = min * 6;
         var calc_sec = sec * 6;

         hour.style.transform = "rotate(" + calc_hr + "deg)";
         minute.style.transform = "rotate(" + calc_min + "deg)";
         seconds.style.transform = "rotate(" + calc_sec + "deg)";
      }, 1000);
   </script>
</body>
</html>

The above is the detailed content of How to create an analog clock using HTML, CSS and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)