use JavaScript To make a real-time clock

The renderings are as follows :

Next , Step by step, I'll show you how to make , And put forward some noteworthy matters .

The first is to build up the framework ,

<div>
<canvas id="canvas" width="500px" height="500px"></canvas>
</div>
<!--
Put one on the outside div The main function is to center the canvas , It looks better this way
-->

Then give div and canvas The style of :

div{
text-align: center;
margin-top: 150px;
}
/*canvas{
border: 1px solid #000;
}*/
/* Give the canvas a border , Mainly used to adjust the position of the canvas */

Get the width and height of the canvas , In this way, when we change later, the following content can be changed automatically , Write the code alive ,

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
// Get the width and height of the canvas
var width = canvas.width;
var height = canvas.height;
// Get the radius of the circle
var r = width / 2;

And the origin of the entire canvas (0,0) The position of , This is conducive to the calculation of the back position .

translate(x,y); take x And y The coordinates of the points are redefined as the origin of the canvas .

context.translate(r,r);

After the origin has been determined, you can draw a circle

context.arc(0,0,r - 6,0,Math.PI * 2);
context.arc(x,y,r,sAngle,eAngle,counterclockwise);
Parameters describe
x The center of a circle x coordinate .
y The center of a circle y coordinate .
r The radius of the circle .
sAngle Starting angle , In radians .( The three o'clock position of the circle of the arc is 0 degree ).
eAngle End angle , In radians .
counterclockwise Optional . Specify whether the drawing should be counter clockwise or clockwise .False = Clockwise ,true = Anti-clockwise .

Then choose the drawing method , There are two ways to draw :

1 context.stroke()----- Stroke

2 context.fill()----- fill

// Stroke 
context.arc(100,100,50,0,2* Math.PI);
context.strokeStyle = "#00FFFF";
context.stroke();
// fill
context.beginPath();
context.arc(300,300,50,0,2* Math.PI);
context.closePath();
context.fillStyle = "#FF00FF";
context.fill();

design sketch :

It is worth noting that , At the beginning of the second drawing path , Have to add

context.beginPath();     and

context.closePath();

otherwise , It will affect the drawing of the following styles .

The next step is to 12 Put a number in the corresponding position of the circle , thus , We're going to calculate the... Of each position x Coordinates and y coordinate .

That's what we need Math.sin() and Math.cos() function .

 // obtain x,y coordinate , And will 12 Write the number to the corresponding position 
var hournum = [3,4,5,6,7,8,9,10,11,12,1,2];
for(var i = 0; i< hournum.length; i++){
// The angle of clockwise rotation ( Radian system )
var rad = 2 * Math.PI / 12 * i;
var x = (r - 30) * Math.cos(rad); // obtain x coordinate
var y = (r - 30) * Math.sin(rad); // obtain y coordinate
context.fillText(hournum[i],x,y);
}
// draw 60 A little bit
for(var j = 0; j< 60; j++){
// The rotation angle of the minute hand ( Radian system )
var rad = 2 * Math.PI / 60 * j;
var x = (r - 18) * Math.cos(rad); // obtain x coordinate
var y = (r - 18) * Math.sin(rad); // obtain y coordinate
context.beginPath();
if(j % 5 === 0){ // stay 3 6 9 12 Location , Set the color of the dot to a darker color , It can be distinguished from other colors
context.fillStyle = "#0f0f0f";
}else{
context.fillStyle = "#f0883a";
}
context.arc(x,y,3,0,Math.PI * 2);
context.closePath();
context.fill();
}

Behind it is the hour hand , minute hand , The drawing of the second hand , The three are basically the same , I'll give you the specific drawing method of the hour hand :

// Draw the hour hand 
function drawHour(hour,minu){
context.save(); // Save the current environment
context.beginPath();
var rad_h = 2 * Math.PI / 12 * hour;
var rad_m = 2 * Math.PI / 12 / 60 * minu; // The rotation of the hour hand is affected by the minute hand
context.rotate(rad_h + rad_m);
context.lineWidth = 6; // The width of the hour hand
context.moveTo(0,7); // The starting point of the hour hand
context.lineTo(0,-r / 2); // The end of the hour hand
context.lineCap = "round"; // Set the end shape If the cap is set , There can't be a closed path
context.strokeStyle = "#000";
context.stroke();
context.restore(); // Return to the previously saved environment
}

The way to draw a nail is to draw a circle , There's already a way to draw circles , I won't give a detailed introduction here .

Then we get the system time and , The call to the above function .

// Get real time 
function timer(){
context.clearRect(0,0,width,height); // Clear the previous drawing
var now_time = new Date(); // Get current system time
var hour = now_time.getHours(); // Get the current time
var minu = now_time.getMinutes(); // Get the current score
var sec = now_time.getSeconds(); // Get the current second
fun();
drawHour(hour,minu);
drawMinu(minu,sec);
drawSec(sec);
draw();
context.restore(); // Return to the previously saved environment
}

Finally, set a timer , The time interval is set to 1000ms Call once , In this way, the clock is realized .

setInterval(timer,1000);

Here's what we should pay attention to :

1. Application of two functions :

save()   ----    Save the current environment state

restore()   -----    Return the saved environmental state between

2. When calculating coordinates , Of two functions "()" It's a radian system , That is to say π In the form of .

Native javascript More about making clocks

  1. How to use iframe Labels and Javascript Making clocks ?

    How to use it iframe Labels and Javascript Making clocks ? How to make a clock ? The effect is shown below : The clock here goes on and on , But the page below won't become , That's what we want . I will divide it into the following aspects ...

  2. JavaScript Making clock effects

    Requirement specification : Making display year . month . Japan . What day of the week and show the morning (AM) And afternoon (PM) Of 12 The clock in decimal , The specific effect is shown below : The code is as follows : <!DOCTYPE HTML PUBLIC "-//W3C// ...

  3. Native javascript Production of provincial and municipal three-level linkage detailed course

    Multi level linkage pull-down menu is a common effect in the front end , The three-level linkage of provinces and cities is the most typical case . Multi level linkage is generally associated with data , According to the data to generate and modify the linkage of the drop-down menu . Complete a multi-level linkage effect , Help enhance the ability to process data . This example is based on ...

  4. Native javascript Make canvas Verification Code

    <canvas id="></canvas> <a href="#" id="changeImg"> Can't see , In a ...

  5. canvas : Native javascript Write a dynamic clock

    canvas : Native javascript Write a dynamic clock     At this point, the needle is centered on the center of the canvas : g.translate(width/2,width/2); This function moves the origin of the canvas to (width/2,wid ...

  6. Use Native js Make plug-ins (javaScript Music player )

    1. Reference page index.html <!DOCTYPE html> <html lang="en"> <head> <meta chars ...

  7. utilize css+ Native js Making simple clocks and watches

    utilize css+ Native js Make simple clocks . The effect is as follows Achieve this effect , It's divided into three parts :html.javascript.css html part html Part is simple , Define a clock Of div, There's an origin inside . Time, second hand . date ...

  8. Native javascript Realization animate

    Native javascript Realization animate //animate function getstyle(obj,name){ if(obj.currentStyle){ return obj.curr ...

  9. Talking about Native javaScript&amp;&amp;react Achieve global touch button ( Incidental to addeventlistener Understanding )

    1. Use native javaACript Achieve global touch button First, output... On the console , Observe what touch fields are available for the event , Then start with the data of these fields to write the method . Because what we need to do is to touch the button globally , What I need to get is the coordinates of the button ...

Random recommendation

  1. false Textatea The construction of (div+table), And the corresponding scroll bar problem and safari Optimization on

    Create a non editable block of text in the page , And the length of the text block is large , The first reaction is to create a textarea, And put it's disabled="disabled", And set the corresponding scroll attribute , You can build ...

  2. Java Method trim() Notes

    We usually use trim() The main function of the method , It's to remove the leading and trailing spaces of the string . However, according to my personal experience, I found that ,trim() This method can only remove some spaces or whitespace , For example, half space : For full space , use trim() It doesn't remove ...

  3. const The pointer

    const The pointer problem , Reviewed many times , Every time I read a book, I understand , But after a while it didn't work , Always confused again . So let's use the code to solve this problem , Write down what you understand . The code is below : ; ; const int* ...

  4. 【 turn 】ORACLE Regular clearance INACTIVE conversation

    source address :http://www.cnblogs.com/kerrycode/p/3636992.html ORACLE Database sessions have ACTIVE.INACTIVE.KILLED. CACHED.SNIPE ...

  5. Azkaban 2.5.0 job type Plug in installation

    One . Environment and software Installation environment : The installation directory : /usr/local/ae/ankaban Hadoop The installation directory export HADOOP_HOME=/usr/local/ae/hadoop-1.2.1 ...

  6. PHP How to use SQL Statement to write data to MySQL Database ?

    1,php and MySQL Establish a connection 2, open 3, Accept page data ,PHP Enter into the specified table 1.2 Two steps can directly use a database link file :conn.php <?phpmysql_connect(&qu ...

  7. MyEclipse-File Serarch Times wrong :Problems encountered during text search

  8. 《C++ Primer 4th》 Reading notes The first 10 Chapter - Associate container

    Original article , Reprint please indicate the source :http://www.cnblogs.com/DayByDay/p/3936464.html

  9. 44.Odoo Product analysis ( 5、 ... and ) – Customization (1) – management odoo install (1)

    see Odoo Product analysis series -- Catalog 1 Administrator's notes Be careful when recording important configuration details , And there must be a continuous, appropriate . A plan that enables the system to install backup and run in an acceptable time . 1.1 Develop implementation strategies Such as ...

  10. Vue:( 5、 ... and )axios

    Axios It's based on promise Of HTTP library , Can be used in the browser and node.js in .axios It is mainly used to send requests to the background , And more controllable functions in the request . Official no longer maintain vue-resource, PUSH ...