search
HomeWeb Front-endJS TutorialFive easy steps to implement JavaScript HTML clock effect

This article mainly introduces the five-step code to easily implement JavaScript HTML clock effect. It has certain reference and value for learning JavaScript. Friends who are interested in JavaScript can refer to it. This article

After learning HTML, CSS and JS for a period of time, I will make a beautiful and not powerful HTML clock for everyone. First look at the picture:

The knowledge points involved are: CSS3 animation, DOM operation, timer, calculation of dot coordinates (many people have already returned it to their teachers~)
Next, we use 5 steps To make it

step1,Prepare HTML

First, we need to prepare the HTML structure, background, dial, hands (hour hand, minute hand, second hand), and numbers.

<p id="clock">
 <p class="bg">
  <p class="point">
   <p id="hour"></p>
   <p id="minute"></p>
   <p id="second"></p>
   <p class="circle"></p>
  </p>
 </p>
< /p>

step2, Prepare CSS

Define the color and size of the pointer. What needs to be explained is transform: rotate(-90deg); used to rotate the pointer, transform- origin:0 6px; is used to set the rotation center point.

<style>
 *{
  margin: 0;
  padding: 0;
 }
 #clock{
  margin: 5% auto;
  width: 400px;
  height: 400px;
  border-radius: 10px;
  background: #aaa;
  position: relative;
  transform: rotate(-90deg);
 }
 #clock .bg{
  width: 360px;
  height: 360px;
  border-radius: 50%;
  background: #fff;
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -180px;
  margin-top: -180px;
 }
 #clock .point{
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -14px;
  margin-top: -14px;
 }
 #clock #hour{
  width: 80px;
  height: 16px;
  background: #000;
  margin: 6px 0 0 14px;
  /*transform: rotate(30deg);*/
  transform-origin:0 8px;
  /*animation: hour 3s linear 100!* alternate*!;*/
  border-radius: 16px;
 }

 #clock #minute{
  width: 120px;
  height: 12px;
  background: #000;
  margin: -14px 0 0 14px;
  transform-origin:0 6px;
  border-radius: 12px;
 }
 #clock #second{
  width: 160px;
  height: 6px;
  background: #f00;
  margin: -9px 0 0 14px;
  transform-origin:0 3px;
  border-radius: 6px;
 }
 #clock .point .circle{
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background: #000;
  position: absolute;
  left: 0;
  top: 0;
 }
 @keyframes hour {
  from {transform: rotate(0deg);}
  to {transform: rotate(360deg);}
 }

 #clock .number{
  position: absolute;
  font-size: 34px;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
  transform: rotate(90deg);
 }
< /style>

step3, Calculate the hour hand position

JS obtains the current time through the Date object, getHours obtains the hour, getMinutes obtains the minute, and getSeconds obtains the second. One rotation of the hour hand is 12 divisions, and the angle of each division is 360°/12. The minutes and seconds are both 60 divisions, and the angle of each division is 360°/60.

function clock(){
 var date = new Date();//获取当前时间
 //时(0-23) 分(0-59)秒(0-59)
 //计算转动角度
 var hourDeg = date.getHours()*360/12;
 var minuteDeg = date.getMinutes()*360/60;
 var secondDeg = date.getSeconds()*360/60;
 //console.log(hourDeg, minuteDeg, secondDeg);
 //设置指针
 hour.style.transform = &#39;rotate(&#39;+hourDeg+&#39;deg)&#39;;
 minute.style.transform = &#39;rotate(&#39;+minuteDeg+&#39;deg)&#39;;
 second.style.transform = &#39;rotate(&#39;+secondDeg+&#39;deg)&#39;;
}

step4, Clock rotation

Set the timer through setInterval and refresh it every second. Note that the initialization needs to be executed once, otherwise the effect will not be visible until 1s later.

//初始化执行一次
clock();
setInterval(clock,1000);

step5, Drawing digital time

Digital time is also on a circle. We only need to determine the radius, and then get the coordinates on the radius. Just position each number by the left side. Take a look at the calculation rules of the circular coordinate system:

* Calculation of circular radius coordinates:
* x = pointX + r*cos(angle);
* y = pointY + r*sin(angle);
But note that the coordinates we calculate are the coordinates of the point on the arc. When positioning each number, it is positioned based on the upper left corner point of the element, so that our numbers There will be an offset. That is to say, the center point of the number is not on the arc. The solution is to translate the coordinate point (x, y) by half of itself (x-w/2, y-h/2)
, so that the center point of the number is on the arc. .

var pointX = 200;
var pointY = 200;
var r = 150;
function drawNumber(){
 var deg = Math.PI*2/12;//360°
 for (var i = 1; i <= 12; i++) {
  //计算每格的角度
  var angle = deg*i;
  //计算圆上的坐标
  var x = pointX + r*Math.cos(angle);
  var y = pointY + r*Math.sin(angle);
  //创建p,写入数字
  var number = document.createElement(&#39;p&#39;);
  number.className = &#39;number&#39;;
  number.innerHTML = i;
  //减去自身的一半, 让p的中心点在圆弧上
  number.style.left = x - 25 + &#39;px&#39;;
  number.style.top = y - 25 + &#39;px&#39;;
  //添加到页面
  myClock.appendChild(number);
 }
}

Complete JS code:

<script>
 /***
  * 时钟:
  * 1> 旋转: rotate(90deg)
  * 2> 旋转中心点: transform-origin
  * */
 //TODO step1: 获取时钟的指针
 var hour = document.getElementById(&#39;hour&#39;);//时针
 var minute = document.getElementById(&#39;minute&#39;);//分针
 var second = document.getElementById(&#39;second&#39;);//秒针
 var myClock = document.getElementById(&#39;clock&#39;);//时钟

 //TODO step2: 获取当前时间,把指针放在正确的位置
 function clock(){
  var date = new Date();//获取当前时间
  //时(0-23) 分(0-59)秒(0-59)
  //计算转动角度
  var hourDeg = date.getHours()*360/12;
  var minuteDeg = date.getMinutes()*360/60;
  var secondDeg = date.getSeconds()*360/60;
  //console.log(hourDeg, minuteDeg, secondDeg);
  //设置指针
  hour.style.transform = &#39;rotate(&#39;+hourDeg+&#39;deg)&#39;;
  minute.style.transform = &#39;rotate(&#39;+minuteDeg+&#39;deg)&#39;;
  second.style.transform = &#39;rotate(&#39;+secondDeg+&#39;deg)&#39;;
 }
 //初始化执行一次
 clock();
 //TODO step3: 设置定时器
 setInterval(clock,1000);

 /***
  * 圆半径坐标计算:
  * x = pointX + r*cos(angle);
  * y = pointY + r*sin(angle);
  * */
 var pointX = 200;
 var pointY = 200;
 var r = 150;
 //TODO step4: 画时钟数字
 function drawNumber(){
  var deg = Math.PI*2/12;//360°
  for (var i = 1; i <= 12; i++) {
   //计算每格的角度
   var angle = deg*i;
   //计算圆上的坐标
   var x = pointX + r*Math.cos(angle);
   var y = pointY + r*Math.sin(angle);
   //创建p,写入数字
   var number = document.createElement(&#39;p&#39;);
   number.className = &#39;number&#39;;
   number.innerHTML = i;
   //减去自身的一半, 让p的中心点在圆弧上
   number.style.left = x - 25 + &#39;px&#39;;
   number.style.top = y - 25 + &#39;px&#39;;
   //添加到页面
   myClock.appendChild(number);
  }
 }
 drawNumber();
< /script>

The above is the entire content of this article, I hope it will be helpful to everyone’s learning! !

Related recommendations:

Three implementation methods of JavaScript defined functions

How to use javascript to randomly generate a certain number of passwords

Javascript example of calculating gradient color

The above is the detailed content of Five easy steps to implement JavaScript HTML clock effect. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
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

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

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 Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools