JS Canvas implement round clock tutorial _javascript skills

Source: Internet
Author: User
Tags cos current time setinterval sin

Reading this article needs a little about the basic use of canvas, the example of this article for you to share the HTML5 canvas implementation of the circular clock simple tutorial

Step One: create a new, simplest HTML file and define the element canvas in the <body> tab.

Canvas.html

 
 

After this step is done, open the canvas.html in a browser and you will find that nothing is visible because we do not draw anything on the canvas, nor do we define boundaries for it.

Add CSS style attributes to <canvas> in canvas. HTML:

 
 

In this way, we can see the outline of the <canvas>.

When the width and height are not set, the canvas initializes a width of 300 pixels and a height of 150 pixels. The element can use CSS to define size, but the image will scale to fit its frame size when it is drawn: if the size of the CSS does not match the original canvas, it will distort.

Note: If the image you are drawing is distorted, try to specify width and height in the properties of <canvas>, rather than using CSS.

Step Two: Create a new Draw.js file to draw the circular clock logic and initialize the work.

There is no doubt that to implement the clock, you need to get the system time.

In JS syntax, date () can be used to get time in real time.
var currenttime = new Date ();

Then, you want to master the function of canvas drawing a circle:
Arc (x, y, radius, startangle, Endangle, anticlockwise) This method represents a radius-radius arc (circle) that is centered on (x,y), starting at startangle and ending at Endangle, is generated in the direction given by anticlockwise (the default clockwise (true)).
The units of Stratangle and Endangle are not the units of angle that we are familiar with, but the radian units. A complete circle spans the radian 2π.

In the canvas coordinate system, the x-axis is in the direction of 0 radians. The clock pointer rotates clockwise to 2π as a cycle, so the clock pointer starts at the * π position ( -1/2), as shown in the following illustration.

The current time is calculated in radians as follows:

 A clock cycle of 12 equal to 12 for the remainder is due to date (). Gethours will return an hour of 24 hours.
hour = (currenttime.gethours ()%) * (2 * MATH.PI/12); 
MINUTE One lap 60 equal
MINUTE = (currenttime.getminutes) * (2* math.pi/60); 
SECOND a lap of 60
SECOND = (currenttime.getseconds) * (2 * math.pi/60); 

Because the clock circle starts in canvas ( -1/2) * π, we also need to add ( -1/2) The starting offset of the * π.

Preliminary get Draw.js:

function Draw () {
 //canvas painting premise work
 var canvas = document.getElementById (' clock ');
 var currenttime = new Date ();
 var hour = (Currenttime.gethours ()%12) * MATH.PI/6;
 var minute = currenttime.getminutes () * MATH.PI/30;
 var second = Currenttime.getseconds () * MATH.PI/30;
 hour = Hour-math.pi * (1/2);
 minute = Minute-math.pi * (1/2);
 Second = Second-math.pi * (1/2);
 if (canvas.getcontext) {
  var ctx = Canvas.getcontext (' 2d ');
  Ctx.beginpath ();
  Ctx.arc (200,200,50,math.pi* ( -1/2), hour,false);
  Ctx.moveto (200,100);
  Ctx.arc (200,200,100,math.pi* ( -1/2), minute,false);
  Ctx.moveto (200,50);
  Ctx.arc (200,200,150,math.pi* ( -1/2), second,false);
  Ctx.stroke ();
 }

Add a draw.js reference to the canvas.html at the same time.

 
 

After completing the second step, we can see a circular clock outline for the current time. So the next step is to get it moving!

Step Three: use the Requestanimationframe () method to get the clock moving.

The execution frequency of Requestanimationframe () is 1 seconds and 60 frames, and the user can define events in Requestanimationframe to repeat them in each frame and iterate through the corresponding events.

In our case, the requestanimationframe to do within each frame is simple, adding increments to the three parameters of the current time (hour, minute, second), and then redrawing the clock.

According to the frequency of 60 frames per second, the increment of second in 1 frames is: 2*π/60/60 =π/1800;

The increment of the minute in one frame is one of the 60 points of the second increment; hour the increment in one frame is the minute of 12 1.

In addition: When the hour, minute, second any one by one variables to 3/2*π, meaning that a cycle has been completed, it is necessary to reinitialize ( -1/2) * π, otherwise it will overwrite drawn into a circle.

From this: in the Requestanimationframe () function, the Hour,minute,second update process is as follows:

   var s = math.pi/1800;
   var m = s/60;
   var h = M/12;
   Second = second + s;
   minute = minute + M;
   Hour = hour + H;
   if (Second >= Math.PI * (3/2)) {
    second = Math.PI * ( -1/2);
   }
   if (Minute >= Math.PI * (3/2)) {
    minute = Math.PI * ( -1/2);
   }
   if (Second >= Math.PI * (3/2)) {
    second = Math.PI * ( -1/2);
   } </span>

The complete code for updating Draw.js is as follows:

function Draw () {var canvas = document.getElementById (' clock ');
 var currenttime = new Date ();
 var hour = (Currenttime.gethours ()%12) * MATH.PI/6;
 var minute = currenttime.getminutes () * MATH.PI/30;
 var second = Currenttime.getseconds () * MATH.PI/30;
 hour = Hour-math.pi * (1/2);
 minute = Minute-math.pi * (1/2);
 Second = Second-math.pi * (1/2);
  if (canvas.getcontext) {var ctx = Canvas.getcontext (' 2d ');
  var s = math.pi/1800;
  var m = s/60;
  var h = M/12;
  var rotate = requestanimationframe (step);
   function Step () {second = second + s;
   minute = minute + M;
   Hour = hour + H;
   if (Second >= Math.PI * (3/2)) {second = Math.PI * ( -1/2);
   } if (Minute >= Math.PI * (3/2)) {minute = Math.PI * ( -1/2);
   } if (Second >= Math.PI * (3/2)) {second = Math.PI * ( -1/2);
   } ctx.clearrect (0, 0, 400, 400);
   Ctx.beginpath ();
   Ctx.arc (200,200,50,math.pi* ( -1/2), hour,false);
   Ctx.moveto (200,100); Ctx.arc (200,200,100,math.pi* ( -1/2), Minute,false);
   Ctx.moveto (200,50);
   Ctx.arc (200,200,150,math.pi* ( -1/2), second,false);
   Ctx.stroke ();
  Requestanimationframe (step);
 }
 }
}

By the end of this step, we've got a moving circular clock, and then we'll add a pointer to it.

Fourth Step *: add hand hour, minute hand, second hand.

JS provides us with the Math.Cos (), Math.sin () to compute the location where the pointer arrives, and the units in which they receive the parameters are radians.

 function Draw () {var canvas = document.getElementById (' clock ');
 var currenttime = new Date ();
 var hour = (Currenttime.gethours ()%12) * MATH.PI/6;
 var minute = currenttime.getminutes () * MATH.PI/30;
 var second = Currenttime.getseconds () * MATH.PI/30;
 hour = Hour-math.pi * (1/2);
 minute = Minute-math.pi * (1/2);
 Second = Second-math.pi * (1/2);
  if (canvas.getcontext) {var ctx = Canvas.getcontext (' 2d ');
  var s = math.pi/1800;
  var m = s/60;
  var h = M/12;
  var rotate = requestanimationframe (step);
   function Step () {second = second + s;
   minute = minute + M;
   Hour = hour + H;
   if (Second >= Math.PI * (3/2)) {second = Math.PI * ( -1/2);
   } if (Minute >= Math.PI * (3/2)) {minute = Math.PI * ( -1/2);
   } if (Second >= Math.PI * (3/2)) {second = Math.PI * ( -1/2);
   ///The end of the second hand xs = * Math.Cos (second) + 200;
   ys = Math.sin (second) + 200;
   The end of the minute hand XM = Math.Cos (minute) + 200; YM = Math.sin (minute) + 200;
   The end of the hour XH = Math.Cos (hour) + 200;

   YH = M Math.sin (hour) + 200;
   Ctx.clearrect (0, 0, 400, 400);
   Ctx.beginpath ();
   Draw Pointer Ctx.moveto (200,200);
   Ctx.lineto (Xs,ys);
   Ctx.moveto (200,200);
   Ctx.lineto (XM,YM);
   Ctx.moveto (200,200);
   Ctx.lineto (XH,YH);
   Draw round Contour Ctx.moveto (200,150);
   Ctx.arc (200,200,50,math.pi* ( -1/2), hour,false);
   Ctx.moveto (200,100);
   Ctx.arc (200,200,100,math.pi* ( -1/2), minute,false);
   Ctx.moveto (200,50);
   Ctx.arc (200,200,150,math.pi* ( -1/2), second,false);
   Ctx.stroke ();
  Requestanimationframe (step);

 }
 }
}

Well, although the pointers are drawn, I feel a little regretful because it's so ugly. From an aesthetic point of view, the clock with the pointer should be a full circle contour of the clock. I wonder if the reader has the same feeling. I decided to return the fourth step in step fifth.

The fifth step: personalize, beautify, customize your clock.

The HTML5 Canvas Canvas provides a variety of style attributes, such as line color, line weight, and so on.

In order to improve the reusability of the code, we abstracted the circle-drawing code into a function.

 function Draw () {var canvas = document.getElementById (' clock ');
 var currenttime = new Date ();
 var hour = (Currenttime.gethours ()%12) * MATH.PI/6;
 var minute = currenttime.getminutes () * MATH.PI/30;
 var second = Currenttime.getseconds () * MATH.PI/30;
 hour = Hour-math.pi * (1/2);
 minute = Minute-math.pi * (1/2);
 Second = Second-math.pi * (1/2);
  if (canvas.getcontext) {var ctx = Canvas.getcontext (' 2d ');
  var s = math.pi/1800;
  var m = s/60;
  var h = M/12;
  var rotate = requestanimationframe (step);
   function Step () {second = second + s;
   minute = minute + M;
   Hour = hour + H;
   if (Second >= Math.PI * (3/2)) {second = Math.PI * ( -1/2);
   } if (Minute >= Math.PI * (3/2)) {minute = Math.PI * ( -1/2);
   } if (Second >= Math.PI * (3/2)) {second = Math.PI * ( -1/2);
   } ctx.clearrect (0, 0, 400, 400);
   Ctx.beginpath ();
   Draw round Contour drawcircle (CTX, hour, ' #99ff00 ');
   Drawcircle (CTX, Minute, ' #99ff66 '); DrawcirCLE (CTX, 140, second, ' #66cc66 ');
  Requestanimationframe (step);
 }} function Drawcircle (CTX, radius, endangle, color) {Ctx.beginpath ();
 Ctx.moveto (200,200-radius);
 Ctx.strokestyle = color;
 Ctx.linewidth = 20;
 Ctx.arc (200,200,radius,math.pi* ( -1/2), endangle,false);
Ctx.stroke (); 

 }

Step Sixth (add later): Add a digital index to the clock.

The concrete approach is to add a canvas canvas element. Since we can get time from date (), it is not a problem to show the source of the value. The only thing readers need to know is to use the SetInterval (Thingstodo (), interval) method to update the index per second.

The modified canvas.html


function Draw () {var canvas = document.getElementById (' clock ');
 var Displaycanvas = document.getElementById (' Display ');
 var currenttime = new Date ();
 var hour = (Currenttime.gethours ()%12) * MATH.PI/6;
 var minute = currenttime.getminutes () * MATH.PI/30;
 var second = Currenttime.getseconds () * MATH.PI/30;
 hour = Hour-math.pi * (1/2);
 minute = Minute-math.pi * (1/2);
 Second = Second-math.pi * (1/2);
  if (canvas.getcontext) {var ctx = Canvas.getcontext (' 2d ');
  var ctxd = Displaycanvas.getcontext (' 2d ');
  Showdisplay (Ctxd, currenttime);
  var s = math.pi/1800;
  var m = s/60;
  var h = M/12;
  var rotate = requestanimationframe (step);
   function Step () {second = second + s;
   minute = minute + M;
   Hour = hour + H;
   if (Second >= Math.PI * (3/2)) {second = Math.PI * ( -1/2);
   } if (Minute >= Math.PI * (3/2)) {minute = Math.PI * ( -1/2);
   } if (Second >= Math.PI * (3/2)) {second = Math.PI * ( -1/2); } ctx.clearrect (0, 0, 400, 400);
   Ctx.beginpath ();
   Draw round Contour drawcircle (CTX, hour, ' #99ff00 ');
   Drawcircle (CTX, Minute, ' #99ff66 ');
   Drawcircle (CTX, 140, second, ' #66cc66 ');
  Requestanimationframe (step);
 }} function Drawcircle (CTX, radius, endangle, color) {Ctx.beginpath ();
 Ctx.moveto (200,200-radius);
 Ctx.strokestyle = color;
 Ctx.linewidth = 20;
 Ctx.arc (200,200,radius,math.pi* ( -1/2), endangle,false);
Ctx.stroke ();
 function Showdisplay (CTX, date) {var h = date.gethours (), M = Date.getminutes (), S = date.getseconds ();
 Timed Text Style Ctx.font = "13px Sans-serif";
 ctx.textalign = "center";
 Ctx.stroketext (h+ ":" +m+ ":" +s,200,200);
  var Timmer = setinterval (function () {s++;
   if (s>=60) {m++;
  s=0;
   } if (m>=60) {h++;
  m=0;
  } if (h>=24) {h=0;
  } ctx.clearrect (0,0,400,400);
 Ctx.stroketext (h+ ":" +m+ ":" +s,200,200);
},1000);

 }

The final outcome chart is as follows:

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.