MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create an analog clock with HTML5

In this article, we will understand some of the basic concepts of HTML5 and then apply these concepts by making an analog clock.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

Before starting, I would like to brief the users with what is HTML5 and some of its basics so that they can have a better understanding.

What is HTML5?

Let us start with a very basic definition of HTML5. It is a markup language which is used for structuring and presenting the content for the World Wide Web. It is the new standard of HTML. Most of the major browsers support many of the new HTML5 elements and APIs.

Some of the key features of HTML5 are:

  • It has the <canvas> element for 2D drawing.
  • It has <video> and <audio> elements for media playback.
  • Local storage support.
  • New content-specific elements, like <article>, <footer>, <header>, <nav>, <section>.
  • New form controls, like calendar, date, time, email, url, search.

Listing 1: Shows the code for syntax of HTML5

<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>

<body>
The content of the document......
</body>

</html>

Before proceeding, firstly we will study about HTML5 canvas and some of its various methods. The HTML5 <canvas> element is used to draw graphics, on the fly, via scripting (usually JavaScript). The <canvas> element is only a container for graphics. Users must use a script to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, characters, and adding images. The methods used in HTML5 canvas are:

lineTo method: The lineTo() method adds a new point and creates a line from that point to the last specified point in the canvas. It should be kept in mind that this method does not draw the line.

Listing 2: Shows the code for lineTo method of HTML5 canvas

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.moveTo(20,20);
ctx.lineTo(20,100);
ctx.lineTo(70,100);
ctx.stroke();
Shows the image for the output of listing 2

Figure 1: Shows the image for the output of listing 2

moveTo method: The moveTo() method moves the path to the specified point in the canvas, without creating a line.

Listing 3: Shows the code for moveTo method of HTML5 canvas

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(300,150);
ctx.stroke();
Shows the image for the output of listing 3

Figure 2: Shows the image for the output of listing 3

Stroke method: To set the stroke text color using HTML5 Canvas. We can set the strokeStyle property of the canvas context to a color string, hex value, or RGB value, and then use the strokeText() method to stroke the text.

Listing 4: Shows the code for using the stroke method

<script>
context.strokeStyle = 'blue';
context.lineWidth = 3;
context.strokeText('Hello World!', x, y);
</script>
Shows the image generated by using listing 4

Figure 3: Shows the image generated by using listing 4

The method of drawing an HTML5 canvas is as follows:

  • In the first step, user needs to set up a canvas in HTML, create a reference, and get the context object. For this, user needs to define <canvas> tag in HTML.
  • The second step is to draw rectangles, straight lines, Bezier curves, circles, and shapes using the above defined methods such as lineTo method, moveTo method and stroke method.
  • In the third step, the bitmap images are displayed. In this the bitmap images such as .jpg, .png, and .gif files can be placed on a canvas.
  • And finally, the gradients are animations are set to it. If the elements are inside the canvas, the setInterval method is used. CSS3 Transitions and Animations can be used to transform the canvas itself or objects outside of the canvas.

So, after having a deep understanding of HTML5 and some of its key features, we will now create an analog clock using the canvas element of HTML and some of the above discussed concepts.

We will start by defining the body of the HTML page.

Listing 5: Shows the code for defining the body of HTML page

<body>
<div><h1>Clock Using HTML5</h1></div>
<canvas id='mycanvas' width='800' height='850'></canvas>
<script src='Clockscript.js' type="text/javascript">
 </script>
</body>

After defining the HTML page, the next thing is to define the functionality using JavaScript. In this, the following functions are used:

  • Createcirlce function is used to draw the circle for the face of the clock.
  • Createnos function to draw numbers on the clock.
  • Createcentre function to draw a small filled circle at the clock centre.
  • Createhand function to draw the lines that represent clock hands.

Listing 6: Shows the code for defining the functions

function createcircle() {
    context.beginPath();
    context.arc(canvas.width / 2, canvas.height / 2, r, 0, Math.PI * 2, true);    
    context.stroke();
}
function createnos() {
    var nos = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
angle = 0,
nowidth = 0;
    nos.forEach(function (numeral) {
        angle = Math.PI / 6 * (numeral - 3);
        nowidth = context.measureText(numeral).width;
        context.fillText(numeral,canvas.width / 2 + Math.cos(angle) * (Hr) -nowidth / 2,canvas.height / 2 + Math.sin(angle) * (Hr) + font / 3);
    });
}
function createcenter() {
    context.beginPath();
    context.arc(canvas.width / 2, canvas.height / 2, 15, 0, Math.PI * 2, true);
    context.fill();
}
function createhand(loc, isHour) {
    var angle = (Math.PI * 2) * (loc / 60) - Math.PI / 2, handRadius = isHour ? r - x - Hx : r - x;
    context.moveTo(canvas.width / 2, canvas.height / 2);
    context.lineTo(canvas.width / 2 + Math.cos(angle) * handRadius, canvas.height / 2 + Math.sin(angle) * handRadius); 
    context.stroke();
}
function createhands() {
    var date = new Date,
hour = date.getHours();
    hour = hour > 12 ? hour - 12 : hour;
    createhand(hour * 5 + (date.getMinutes() / 60) * 5, true, 0.5);
    createhand(date.getMinutes(), false, 0.5);
    createhand(date.getSeconds(), false, 0.2);
}
function createclock() {
    context.clearRect(0, 0, canvas.width, canvas.height);
    createcircle();
    createcenter();
    createhands();
createnos();
}

In the last step, we will be using CSS in the Head section of the HTML to provide the look and formatting of our HTML page.

Listing 7: Shows the code do the last step

<head>
    <title>Clock</title>
    <style>
    body
    {background:white;
     border:black;
     cursor:crosshair
        }
        #mycanvas
        {background:pink;
         border:thick solid #aaaaaa;
            }
    </style>
</head>

Finally, the complete code will be like this:

Listing 8: Shows the complete code

//HTML Code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Clock</title>
    <style>
    body
    {background:white;
     border:black;
     cursor:crosshair
        }
        #mycanvas
        {background:pink;
         border:thick solid #aaaaaa;
            }
    </style>
</head>
<body>
<div><h1>Clock Using HTML5</h1></div>
<canvas id='mycanvas' width='800' height='850'></canvas>
<script src='Clockscript.js' type="text/javascript">
 </script>
</body>
<html>

//JavaScript Code
var canvas = document.getElementById('mycanvas'),
context = canvas.getContext('2d'),
font = 35,
padding = 35,
x = canvas.width / 25,
Hx = canvas.width / 10,
space = 20,
r = canvas.width / 2 - padding,
Hr = r + space;
function createcircle() {
    context.beginPath();
    context.arc(canvas.width / 2, canvas.height / 2, r, 0, Math.PI * 2, true);    
    context.stroke();
}
function createnos() {
    var nos = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
angle = 0,
nowidth = 0;
    nos.forEach(function (numeral) {
        angle = Math.PI / 6 * (numeral - 3);
        nowidth = context.measureText(numeral).width;
        context.fillText(numeral,canvas.width / 2 + Math.cos(angle) * (Hr) -nowidth / 2,canvas.height / 2 + Math.sin(angle) * (Hr) + font / 3);
    });
}
function createcenter() {
    context.beginPath();
    context.arc(canvas.width / 2, canvas.height / 2, 15, 0, Math.PI * 2, true);
    context.fill();
}
function createhand(loc, isHour) {
    var angle = (Math.PI * 2) * (loc / 60) - Math.PI / 2, handRadius = isHour ? r - x - Hx : r - x;
    context.moveTo(canvas.width / 2, canvas.height / 2);
    context.lineTo(canvas.width / 2 + Math.cos(angle) * handRadius, canvas.height / 2 + Math.sin(angle) * handRadius); 
    context.stroke();
}
function createhands() {
    var date = new Date,
hour = date.getHours();
    hour = hour > 12 ? hour - 12 : hour;
    createhand(hour * 5 + (date.getMinutes() / 60) * 5, true, 0.5);
    createhand(date.getMinutes(), false, 0.5);
    createhand(date.getSeconds(), false, 0.2);
}
function createclock() {
    context.clearRect(0, 0, canvas.width, canvas.height);
    createcircle();
    createcenter();
    createhands();
    createnos();
}
context.font = font + 'px Arial';
loop = setInterval(createclock, 1000);

Finally, the created analog clock will be like this.

Shows the final program output

Figure 4: Shows the final program output

Conclusion

Finally, in this article, we have learnt about the basic HTML5, its key features and syntax . We have also learnt the key methods of HTML5 canvas such as moveTo method, lineTo method.



I am well versed with Computer Programming languages and possess good working knowledge on software languages such as C, Java, PHP, HTML and CSS

What did you think of this post?
Services
Know how to keep MrBool Online
SUPPORT US
SUPPORT US
With your help, we can keep providing free content and helping you to be a better professional
support us
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login