Introduction to HTML5 Canvas Tag

556
SHARES
2.5k
VIEWS

What is HTML5 Canvas?

Canvas was originally created by Apple in 2004 to implement Dashboard widgets and to power graphics in the Safari browser, and was later adopted by Firefox, Opera, and Google Chrome. Today, canvas is a part of the new HTML5 specification for next generation web technologies.

The HTML5 canvas is an HTML tag that you can embed inside an HTML document for the purpose of drawing graphics with JavaScript. Since the HTML5 canvas is a bitmap, every pixel drawn onto the canvas overrides pixels beneath it.

Here is the base template for all of the 2D HTML5 Canvas:

<!DOCTYPE HTML>
<html>
    <head>
        <title>HTML5 Canvas Tag</title>
    </head>
    <body>
        <canvas  id="myCanvas" width="600" height="250" style="border:1px solid black;"></canvas>

        <script>
            window.onload = function(){
                var canvas = document.getElementById("myCanvas");
                var ctx = canvas.getContext("2d");
 
                // draw stuff here
            };
        </script>
    </body>
</html>

Notice that the canvas element is embedded inside the body of the HTML document, and is defined with an id, a width, and a height. JavaScript uses the id to reference the canvas tag, and the width and height are used to define the size of the drawing area. Once the canvas tag has been accessed with document.getElementById(), we can then define a 2D context with:

var ctx = canvas.getContext("2d");

Drawing a line

When learning how to draw with the HTML5 canvas for the first time, most people are interested in drawing the most basic and rudimentary element of the canvas. This article will show you how to do just that by drawing a simple straight line.

Define a 2D canvas context and set the line style:

window.onload = function(){
  // get the canvas DOM element by its ID
     var canvas = document.getElementById("myCanvas");
  // declare a 2-d context using the getContext() method of the 
  // canvas object
     var ctx = canvas.getContext("2d");
    
  // set the line width to 10 pixels
     ctx.lineWidth = 10;
  // set the line color to blue
     ctx.strokeStyle = "blue";
};

Position the canvas context and draw the line:

  // position the drawing cursor
     ctx.moveTo(50, canvas.height - 50);
  // draw the line
     ctx.lineTo(canvas.width - 50, 50);
  // make the line visible with the stroke color
     ctx.stroke();

Our Javascript code look Like this:

window.onload = function(){
  // get the canvas DOM element by its ID
     var canvas = document.getElementById("myCanvas");
  // declare a 2-d context using the getContext() method of the 
  // canvas object
     var ctx = canvas.getContext("2d");
    
  // set the line width to 10 pixels
     ctx.lineWidth = 10;
  // set the line color to blue
     ctx.strokeStyle = "blue";
  // position the drawing cursor
     ctx.moveTo(50, canvas.height - 50);
  // draw the line
     ctx.lineTo(canvas.width - 50, 50);
  // make the line visible with the stroke color
     ctx.stroke();
};

Now you see the following line.

Simple HTML5 Canvas Straight Line

Drawing an arc

When drawing with the HTML5 canvas, it’s sometimes necessary to draw perfect arcs. If you’re interested in drawing happy rainbows, smiley faces, or diagrams, this recipe would be a good start for your endeavor.

Follow these steps to draw a simple arc:

Define a 2D canvas context and set the arc style:

window.onload = function(){
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    ctx.lineWidth = 15;
    ctx.strokeStyle = "black"; // line color
};

For Drawing an Arc put this code in the above code lines

ctx.arc(canvas.width / 2, canvas.height / 2 + 40, 80, 1.1 * Math.PI, 1.9 * Math.PI, false);
ctx.stroke();

Our code look like this:

window.onload = function(){
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    ctx.lineWidth = 15;
    ctx.strokeStyle = "black"; // line color
    ctx.arc(canvas.width / 2, canvas.height / 2 + 40, 80, 1.1 * Math.PI, 1.9 * Math.PI, false);
    ctx.stroke();
};

Now you’ll see the following screen on the browser.

Simple HTML5 Canvas Arc

How Arc works…

We can create an HTML5 arc with the arc() method which is defined by a section of the circumference of an imaginary circle. Take a look at the following diagram:

Diagram

The imaginary circle is defined by a center point and a radius. The circumference section is defined by a starting angle, an ending angle, and whether or not the arc is drawn counter-clockwise:

 ctx.arc(centerX,centerY, radius, startingAngle, endingAngle, counterclockwise);

Notice that the angles start with 0π at the right of the circle and move clockwise to 3π/2, π, π/2, and then back to 0. For this recipe, we’ve used 1.1π as the starting angle and 1.9π as the ending angle. This means that the starting angle is just slightly above center on the left side of the imaginary circle, and the ending angle is just slightly above center on the right side of the imaginary circle.

Drawing a Quadratic curve

In this recipe, we’ll learn how to draw a Quadratic curve. Quadratic curves provide much more flexibility and natural curvatures compared to its cousin, the arc, and are an excellent tool for creating custom shapes.

Define a 2D canvas context and set the curve style:

window.onload = function(){
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
  
    ctx.lineWidth = 10;
    ctx.strokeStyle = "black"; // line color
};

Position the canvas context and draw the Quadratic curve:

 ctx.moveTo(100, canvas.height - 50);
 ctx.quadraticCurveTo(canvas.width / 2, -50, canvas.width - 100, canvas.height - 50);
 ctx.stroke();

Our code look like this:

window.onload = function(){
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
  
    ctx.lineWidth = 10;
    ctx.strokeStyle = "black"; // line color
    ctx.moveTo(100, canvas.height - 50);
    ctx.quadraticCurveTo(canvas.width / 2, -50, canvas.width - 100, canvas.height - 50);
    ctx.stroke();
};

Quadratic curve look like this

Simple HTML5 Canvas Quadratic curve

How it works…

HTML5 Quadratic curves are defined by the context point, a control point, and an ending point:

 ctx.quadraticCurveTo(controlX, controlY, endingPointX, endingPointY);

Take a look at the following diagram:

Diagram

The curvature of a Quadratic curve is defined by three characteristic tangents. The first part of the curve is tangential to an imaginary line that starts with the context point and ends with the control point. The peak of the curve is tangential to an imaginary line that starts with midpoint 1 and ends with midpoint 2. Finally, the last part of the curve is tangential to an imaginary line that starts with the control point and ends with the ending point.

Muhammad Mubeen

Muhammad Mubeen

Mubeen is a full-stack web & mobile app developer who is very proficient in MEAN.js, Vue, Python, Ionic 4, Flutter, Firebase, ROR, and PHP. He has created multiple mobile and web applications. He is very passionate about sharing his knowledge.

Leave a Reply

Your email address will not be published. Required fields are marked *