12 min read

In this article by Syed Omar Faruk Towaha, author of the book JavaScript Projects for Kids, we will discuss about HTML, HTML canvas, implementing JavaScript codes on our HTML pages, and few JavaScript operations.

(For more resources related to this topic, see here.)

HTML

HTML is a markup language. What does it mean? Well, a markup language processes and presents texts using specific codes for formatting, styling, and layout design. There are lots of markup languages; for example, Business Narrative Markup Language (BNML), ColdFusion Markup Language (CFML), Opera Binary Markup Language (OBML), Systems Biology Markup Language (SBML), Virtual Human Markup Language (VHML), and so on. However, in modern web, we use HTML. HTML is based on Standard Generalized Markup Language (SGML). SGML was basically used to design document papers.

There are a number of versions of HTML. HTML 5 is the latest version. Throughout this book, we will use the latest version of HTML.

Before you start learning HTML, think about your favorite website. What does the website contain? A few web pages? You may see some texts, few images, one or two text field, buttons, and some more elements on each of the webpages. Each of these elements are formatted by HTML.

Let me introduce you to a web page. On your Internet browser, go to https://www.google.com. You will see a page similar to the following image:

The first thing that you will see on the top of your browser is the title of the webpage:

  • Here, the marked box, 1, is the title of the web page that we loaded.
  • The second box, 2, indicates some links or some texts.
  • The word Google in the middle of the page is an image.
  • The third box, 3, indicates two buttons.
  • Can you tell me what Sign in on the right-hand top of the page is? Yes, it is a button.

Let’s demonstrate the basic structure of HTML. The term tag will be used frequently to demonstrate the structure.

An HTML tag is nothing but a few predefined words between the less than sign (<) and the greater than sign (>). Therefore, the structure of a tag is <WORD>, where WORD is the predefined text that is recognized by the Internet browsers. This type of tag is called open tag. There is another type of tag that is known as a close tag. The structure of a close tag is as </WORD>. You just have to put a forward slash after the less than sign.

After this section, you will be able to make your own web page with a few texts using HTML. The structure of an HTML page is similar to the following image:

This image has eight tags. Let me introduce all these tags with their activities:

  • 1:This is the <html> tag, which is an open tag and it closes at line 15 with the </html> tag.
    • These tags tell your Internet browser that all the texts and scripts in these two tags are HTML documents.
  • 2:This is the <head> tag, which is an open tag and closes at line 7 with the </head> tag.
    • These tags contain the title, script, style, and metadata of a web page.
  • 3:This is the <title> tag, which closes at line 6 with the </title> tag.
    • This tag contains the title of a webpage. The previous image had the title Google. To see this on the web browser you need to type like that:
      <title> Google </title>
  • 4:This is the close tag of <title> tag
  • 5:This is the closing tag of <head> tag
  • 6:This is the <body> tag, closes at line 13 with tag </body>
    • Whatever you can see on a web page is written between these two tags. Every element, image, link, and so on are formatted here. To see This is a web page on your browser, you need to type similar to the following:
          <body>
      This is a web page
      </body>
  • 7:The </body> tag closes here.
  • 8:The </html> tag is closed here.

Your first webpage

You have just learned the eight basic tags of an HTML page. You can now make your own web page. How? Why not you try with me?

  1. Open your text editor.
  2. Press Ctrl + N, which will open a new untitled file as shown in the following image:
  3. Type the following HTML codes on the blank page:
     <html>
    
        <head>
    
          <title>
    
            My Webpage!
    
          </title>
    
        </head>
    
        <body>
    
          This is my webpage :)
    
        </body>
    
      </html>
  4. Then, press Ctrl + Shift + S that will tell you to save your code somewhere on your computer, as follows:
  5. Type a suitable name on the File Name: field. I would like to name my HTML file webpage, therefore, I typed webpage.html. You may be thinking why I added an .html extension.

    As this is an HTML document, you need to add .html or .htm after the name that you give to your webpage.

  6. Press the Save button.This will create an HTML document on your computer. Go to the directory, where you saved your HTML file.

Remember that you can give your web page any name. However, this name will not be visible on your browser. It is not the title of your webpage. It is a good practice not to keep a blank space on your web page’s name. Consider that you want to name your HTML file This is my first webpage.html. Your computer will face no trouble showing the result on the Internet browsers; however, when your website will be on a server, this name may face a problem. Therefore, I suggest you to keep an underscore (_) where you need to add a space similar to the following: This_is_my_first_webpage.html.

You will find a file similar to the following image:

Now, double-click on the file. You will see your first web page on your Internet browser!

You typed My Webpage! between the <title> and </title> tags, which is why your browser is showing this in the first selection box, 1. Also, you typed This is my webpage 🙂 between the <body> and </body> tags. Therefore, you can see the text on your browser in the second selection box, 2.

Congratulations! You created your first web page!

You can edit your codes and other texts of the webpage.html file by right-clicking on the file and selecting Open with Atom. You must save (Ctrl + S) your codes and text before reopening the file with your browser.

Implementing Canvas

To add canvas on your HTML page, you need to define the height and width of your canvas in the <canvas> and </canvas> tags as shown in the following:

<html>

  <head>

    <title>Canvas</title>

  </head>

  <body>

  <canvas id="canvasTest" width="200" height="100" 
    style="border:2px solid #000;">

 

    </canvas>

  </body>

</html>

We have defined canvas id as canvasTest, which will be used to play with the canvas. We used the inline CSS on our canvas. A 2 pixel solid border is used to have a better view of the canvas.

Adding JavaScript

Now, we are going to add few lines of JavaScript to our canvas. We need to add our JavaScript just after the <canvas>…</canvas> tags in the <script> and </script> tags.

Drawing a rectangle

To test our canvas, let’s draw a rectangle in the canvas by typing the following codes:

<script type="text/javascript">

  var canvas = document.getElementById("canvasTest"); //called our 
    canvas by id

  var canvasElement = canvas.getContext("2d"); // made our canvas 
    2D

  canvasElement.fillStyle = "black"; //Filled the canvas black

  canvasElement.fillRect(10, 10, 50, 50); //created a rectangle

</script>

In the script, we declared two JavaScript variables. The canvas variable is used to hold the content of our canvas using the canvas ID, which we used on our <canvas>…</canvas> tags. The canvasElement variable is used to hold the context of the canvas. We made fillStyle black so that the rectangle that we want to draw becomes black when filled. We used canvasElement.fillRect(x, y, w, h); for the shape of the rectangle. Where x is the distance of the rectangle from the x axis, y is the distance of the rectangle from the y axis. The w and h parameters are the width and height of the rectangle, respectively.

The full code is similar to the following:

<html>

  <head>

    <title>Canvas</title>

  </head>

  <body>

    <canvas id="canvasTest" width="200" height="100" 
      style="border:2px solid #000;">

    </canvas>

    <script type="text/javascript">

      var canvas = document.getElementById("canvasTest"); //called 
        our canvas by id

      var canvasElement = canvas.getContext("2d"); // made our 
        canvas 2D

      canvasElement.fillStyle = "black"; //Filled the canvas black

      canvasElement.fillRect(10, 10, 50, 50); //created a 
        rectangle

    </script>

  </body>

</html>

The output of the code is as follows:

Drawing a line

To draw a line in the canvas, you need to insert the following code in your <script> and </script> tags:

<script type="text/javascript">

  var c = document.getElementById("canvasTest");

  var canvasElement = c.getContext("2d");

  canvasElement.moveTo(0,0);

  canvasElement.lineTo(100,100);

  canvasElement.stroke();

</script>

Here, canvasElement.moveTo(0,0); is used to make our line start from the (0,0) co-ordinate of our canvas. The canvasElement.lineTo(100,100); statement is used to make the line diagonal. The canvasElement.stroke(); statement is used to make the line visible.

Here is the output of the code:

A quick exercise

  • Draw a line using canvas and JavaScript that will be parallel to the y axis of the canvas
  • Draw a rectangle having 300 px height and 200 px width and draw a line on the same canvas touching the rectangle.

Assignment operators

An assignment operator assigns a value to an operator. I believe you that already know about assignment operators, don’t you? Well, you used an equal sign (=) between a variable and its value. By doing this, you assigned the value to the variable.

Let’s see the following example:

Var name = "Sherlock Holmes"

The Sherlock Holmes string is assigned to the name variable. You already learned about the increment and decrement operators. Can you tell me what will be the output of the following codes:

var x = 3;

x *= 2;

document.write(x);

The output will be 6.

Do you remember why this happened?

The x *= 2; statement is similar to x = x * 2; as x is equal to 3 and later multiplied by 2. The final number (3 x 2 = 6) is assigned to the same x variable. That’s why we got the output as shown in the following screenshot:

Let’s perform following exercise:

What is the output of the following codes:

var w = 32;

var x = 12;

var y = 9;

var z = 5;

w++;

w--;

x*2;

y = x;

y--;

z%2;

document.write("w = "+w+", x = "+x+", y = "+y+", z = "+z);

The output that we get is w = 32, x = 12, y = 11, z = 5.

JavaScript comparison and logical operators

If you want to do something logical and compare two numbers or variables in JavaScript, you need to use a few logical operators. The following are a few examples of the comparison operators:

Operator Description
== Equal to
!= Not equal to
> Greater than
< Less than
=> Equal to or greater than
<= Less than or equal to

The example of each operator is shown in the following screenshot:

According to mozilla.org, “Object-oriented programming (OOP) is a programming paradigm that uses abstraction to create models based on the real world. OOP uses several techniques from previously established paradigms, including modularity, polymorphism, and encapsulation.” Nicholas C. Zakas states that “OOP languages typically are identified through their use of classes to create multiple objects that have the same properties and methods.”

You probably have assumed that JavaScript is an object-oriented programming language. Yes, you are absolutely right. Let’s see why it is an OOP language. We call a computer programming language object oriented, if it has the following few features:

  • Inheritance
  • Polymorphism
  • Encapsulation
  • Abstraction

Before going any further, let’s discuss objects. We create objects in JavaScript in the following manner.

var person = new Object();

person.name = "Harry Potter";

person.age = 22;

person.job = "Magician";

We created an object for person. We added a few properties of person.

If we want to access any property of the object, we need to call the property.

Consider that you want to have a pop up of the name property of the preceding person object. You can do this with the following method:

person.callName = function(){

 alert(this.name);

};

We can write the preceding code as the following:

var person = {

  name: "Harry Potter",

  age: 22,

  job: "Magician",

  callName: function(){

    alert(this.name);

  }

};

Inheritance in JavaScript

Inherit means derive something (characteristics, quality, and so on) from one’s parents or ancestors. In programming languages, when a class or an object is based on another class or object in order to maintain the same behavior of mother class or object is known as inheritance.

We can also say that this is a concept of gaining properties or behaviors of something else.

Suppose, X inherits something from Y, it is like X is a type of Y.

JavaScript occupies the inheritance capability. Let’s see an example. A bird inherits from animal as a bird is a type of animal. Therefore, a bird can do the same thing as an animal.

This kind of relationship in JavaScript is a little complex and needs a syntax. We need to use a special object called prototype, which assigns the properties to a type. We need to remember that only function has prototypes. Our Animal function should look similar to the following:

function Animal(){

//We can code here.

};

To add few properties to the function, we need to add a prototype, as shown in the following:

Animal.prototype.eat = function(){

alert("Animal can eat.");

};

Summary

In this article, you have learned how to write HTML code and implement JavaScript code with the HTML file and HTML canvas. You have learned a few arithmetic operations with JavaScript. The sections in this article are from different chapters of the book, therefore, the flow may look like not in line. I hope you read the original book and practice the code that we discussed there.

Resources for Article:


Further resources on this subject:


LEAVE A REPLY

Please enter your comment!
Please enter your name here