HTML5 using canvas to draw a clock sample

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

Preparatory work

Specify a zone in HTML to place the clock:

<div id= "Clock" style= "position:relative;" ></div>

Some of the appearance of the clock set:

var width = 260; Table cloth width
var height= 260;//tablecloth height
var dot = {
x:width/2,
y:height/2,
radius:6
  
   }; Dot position, radius
var radius = 120;//Circle radius
var borderwidth = 6;//round border width
  

Create <canvas> elements:

var clock = document.getElementById (' clock ');
var clockbg = document.createelement (' canvas ');
var clockpointers = document.createelement (' canvas ');
Clockpointers.width = Clockbg.width = width;
Clockpointers.height = Clockbg.height = height;
clockPointers.style.position = ' absolute ';
ClockPointers.style.left = 0;
clockPointers.style.right = 0;
Clock.appendchild (CLOCKBG);
Clock.appendchild (clockpointers);

To create two <canvas> elements here, the purpose is to separate the disk of the clock from the pointer. This is because the pointer erases the redraw based on the current time, and if placed in a <canvas>, the disc is erased when it is erased.

Draw a disk

Whenever you want to draw in <canvas>, you first get its context, and the corresponding interface is Canvas.getcontext:

var bgctx = Clockbg.getcontext (' 2d ');

The only valid argument for the current Canvas.getcontext interface is ' 2d ', which should support 3D drawings in the future.

First, draw the outermost circle box:

Bgctx.beginpath ();
Bgctx.linewidth = borderwidth;
Bgctx.strokestyle = ' #000 ';
Bgctx.arc (Dot.x, Dot.y, radius, 0, 2 * Math.PI, true);
Bgctx.stroke ();
Bgctx.closepath ();

Call Context.beginpath () new Path;
Set colors and other styles;
Call path function to generate path;
Draw Line (stroke) or fill (fill);
Call Context.closepath () to close the path;
The Context.arc interface used above can generate an ARC path, which is described in detail here.

In a similar way, draw a dot:

Bgctx.beginpath ();

Bgctx.fillstyle = ' #000 ';

Bgctx.arc (Dot.x, Dot.y, Dot.radius, 0, 2 * Math.PI, true);

Bgctx.fill ();

Bgctx.closepath ();

At this point, the results are shown in the following illustration:

Draw Scale

The most complex place is to draw the scale, here to review the mathematical trigonometric functions:

The starting position of the tick is a point on the Circle box, and the first step is to know the coordinates of the point. In the figure above:

sinθ= Ac/ao

cosθ= Oc/ao

Where AO is the circle radius, and the value of theta depends on the scale. 0 is π/2,3 is 0,6 is 3π/2,9 is pi

The position at which the starting point of the tick is obtained is:

x = Dot Horizontal axis + AO * cosθ
y = dot ordinate + AO * sinθ
Similarly, the position of the tick end point is calculated (the end point is equivalent to a circle with a radius of round radius-tick length):

x = Dot Horizontal axis + (AO-scale length) * cosθ
y = dot ordinate + (AO-scale length) * sinθ
So, this program can write:

for  (var i = 0, angle = 0, tmp, len; i < 60;  i++)  {    bgctx.beginpath ()     //  highlight the scale that can be removed by 5      if  (0 === i % 5)  {       
 bgCtx.lineWidth = 5;
        len = 12;
        bgCtx.strokeStyle =  ' #000 ';     } else {        bgctx.linewidth
 = 2;
        len = 6;
        bgCtx.strokeStyle =  ' #999 ';     }     tmp = radius - borderWidth / 2;  //  because the circle has a border, subtract the border width     bgctx.moveto (    &nBsp;   dot.x + tmp * math.cos (angle),       
  dot.y + tmp * math.sin (angle)     );
    tmp -= len;     bgctx.lineto (Dot.x + tmp * math.cos (angle),  dot.y +
 tmp * math.sin (angle));
    bgctx.stroke ();
    bgctx.closepath ();     angle += Math.PI / 30; //  Increment 1/30π} at a time

After drawing the scale, the result should be this:

Clock tick

Draw a pointer

First get the context of the pointer <canvas>:

var ptxcontext = Clockpointers.getcontext (' 2d ');
Since the operation of the pointer is performed once every second, this is written as a function to facilitate passing to the setinterval call:

Function updatepointers ()  {    ptctx.clearrect (0, 0, width,   height);   Clear out the original pointer     //  get the current time     var now = new
 date ();
    var h = now.gethours ();
    var m = now.getminutes ();
    var s = now.getseconds ();     //  figure out when the minute pointer should now point to a few points of the circle     h = h > 12
 ? h - 12 : h;
    h = h + m / 60;
    h = h / 12;
    m = m / 60;
    s = s / 60;     drawpointers (s, 2, 92); //  draw seconds     drawpointers (m, 4, 82); //  draw the minute hand     drawPointers (h, 6, 65); //  The Drawpointers function implementation is:// angle is the angle, the linewidth is the pointer width, length is the pointer length Function drawpointers (angle, linewidth, length)  {    angle =
 angle * Math.PI * 2 - Math.PI / 2;
    ptctx.beginpath ();
    ptCtx.lineWidth = lineWidth;
    ptCtx.strokeStyle =  "#000";
    ptctx.moveto (DOT.X,&NBSP;DOT.Y);     ptctx.lineto (Dot.x + length * math.cos (angle),  dot.y +
 length * math.sin (angle));
    ptctx.stroke ();
    ptctx.closepath (); }

This is the main use of trigonometric functions, not? Aluminum playing?? and ⒁?ngel's calculations. Since the incoming angel is a percentage, so multiply a circle, that is 2π, just know the corresponding radian, calculate out later also subtract Π/2, because from the above coordinate diagram can see, 0 is located in the X axis instead of the Y axis, just more than the normal clock more π/2.

Finally, don't forget to call the Updatepointers Live Update pointer:

SetInterval (updatepointers, 1000);

Updatepointers ();

This clock is completely out of the way, in addition to the initial familiarity <canvas> drawing API, but also a review of trigonometric functions.

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.