Canvas Element in HTML

Rubleen Kaur
Last Updated: May 13, 2022

Introduction

Canvas is a resolution-dependent bitmap used for rendering graphs, game graphics, or images on web pages. Most of the developers use the canvas element to create web applications. In simple terms we can say that using Javascript and the canvas element of HTML, we can render 2D shapes and graphs on our websites. Javascript designers can create easy-to-go-free visuals using the canvas element. It consists of a drawable region defined in the HTML code with default height and width. 

 

HTML canvas element and the canvas context are two different things between which most developers are commonly confused. The canvas element is a Document Object Model defined in the HTML, whereas the canvas context is where the drawing or animations are made. 

 

The canvas element just contains the information, but all the drawing is done through Javascript. We can use the element in all the modern browsers which support Javascript rendering. This article will cover the outline of how we can create an HTML canvas element for various shapes and styles. 


 

Let’s dive into the article and learn about the different properties available to use for the HTML canvas element. 

Properties of the <canvas> element

 

The following table depicts the various properties and their usage of the HTML canvas element. It shows the available drawings we can create using the canvas element. 

 

Properties 

Description

To draw rectangles

 

(fillRect, rect(), strokeRect(), clearRect())

It is used to draw rectangle elements by specifying the height and the width of the <canvas> elements. These functions are used to remove, fill and clear a specified rectangle.

To draw paths 

 

(fill(), stroke(), beginPath(), moveTo(), closePath(), lineTo(), clip() )

It is used to make different shapes and paths of <canvas> elements.

To draw lines 

 

lineCap(),lineJoin(), lineWidth() 

 

It is used to create lines using the lineto(), moveto(), and stroke() in the <canva> element
Draw bezier 

bezierCurveTo()
It is used to draw the bezier curve within the <canvas> element.
Draw Quadratic Representation

quadraticCurveTo()
It is used to represent the curve of the quadratic on the <canvas> element.
Use Images

drawImage()
This property allows us to use images in the <canvas> elements

Create Gradients

createLinearGradient(),

createRadialGradient()

This property is used to create gradient colors using the HTML <canvas> element
Add Styles and Colors

strokeStyle(), fillstyle()
This property is used to add styles and colors to the Canvas element

Text and Fonts

 

font(), textAlign(), fillText(), textBaseline(), strokeText()

This property is used to edit the text and fonts on the canvas element on the HTML document.
Patterns and Shadows 

shadowBlur(), shadowColor(), createPattern()
This property is used to add different styles of patterns and shadows on the canvas element.
Canvas States 

save(), restore()
This property is used to store and restore the canvas element
Canvas Animation 

setInterval(), setTimeout(), requestAnimationFrame()
This property is used to add animations on the canvas element using the basic HTML and Javascript.

Canvas Translation

scale(), translate(),

transform()

This property is used to translate the contents on the HTML canvas element.
Canvas Rotation

rotate()
This property is used to rotate the canvas element on the HTML document.

 

Using these properties, we can draw various elements and shapes on the canvas element. We will discuss the basic drawings essential for a developer before exploring more of the canvas element.

 

Designing different elements

Let’s start by creating a canvas of height 300px and width 400px,

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <canvas id ="canvas" height="300" width="400" style = "border: 2px solid black;">
    </canvas>
</body>
</html>

 

Observe we have set the height as 300 and width as 400. To view the canvas, we have styled it with a border of 2px which has solid style and is colored black. We keep an id associated with the canvas to add javascript functionality using the id element. 

 

OUTPUT

 

 

To draw text on the canvas element.

 

We can add text on the canvas element using the fillText() method. This method is used to draw the text on the HTML canvas. We can edit the font using the font property and use the strokeText() method to draw the text on the canvas without filling. 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <canvas id="canvas" width="400" height="300" style="border: 2px solid black;">
    </canvas>
</body>

<script>
    window.onload = function() {
        var c = document.getElementById("canvas");
        var ctx = c.getContext("2d");
        ctx.font = "30px Arial";
        ctx.fillText("Hi Ninja", 40,100);
        ctx.strokeText("Hello World", 10, 50);
    };
</script>
</html>

 

OUTPUT

The above example shows the use of strokeText() and fillText() methods, which have specified the coordinates and the text that is to be displayed on the canvas element. 

 

To draw a line on the canvas element.

We have three methods that are used to draw a line on the canvas, moveTo(), stroke(), and lineTo(). The movesTo() method is used to move the cursor to the element space. The lineTo() method specifies the line’s endpoint, and the stroke() method makes our line visible on the canvas. Here is an example to help you understand the concept better. 

 

<!DOCTYPE html>
<html lang="en">
<head>
<title>Canvas Line </title>

</head>
<body>
    <canvas id="canvas" width="400" height="300" style="border: 2px solid black;">
    </canvas>
</body>
<script>
    window.onload = function() {
        var canvas = document.getElementById("canvas");
        var context = canvas.getContext("2d");
        context.moveTo(10, 250);
        context.lineTo(110, 100);
        context.stroke();
    };
    </script>
</html>

 

OUTPUT



 

NOTE: The points defined in the moveTo,lineTo functions are used to define the X coordinate and the Y coordinate of the line. 

 

To draw a rectangle using the HTML canvas element

 

To draw a rectangle we use the pre-defined javascript methods which are rect(), stroke() and beginpath(). The rect() method is used to create a rectangle. The syntax of the element is:

 

context.rect(x,y,width,height);

 

In the above syntax, the x and y specify the rectangle coordinates, and the width and height are used to make the rectangle with the specifications given attributes. In the below example, we have used the context.strokeStyle method to change the stroke’s color, and we have set it to red to get a colored rectangle border. 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <canvas id="canvas" width="400" height="300" style="border: 2px solid black;">
    </canvas>
</body>

<script>
    window.onload = function() {
    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
    context.strokeStyle = "red";
    context.rect(100,200,200,80);
    context.stroke();
    };
</script>
</html>

 

OUTPUT

 

To draw a circle using the HTML canvas element.

 

To draw a circle, we have a javascript method context. Arc. This method is based on a mathematical formula, and we have the syntax accordingly. The syntax of the element is:

 

context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);

 

In the above syntax, the start angle is set to 0, and the end angle is 2π which would form a complete circle. HTML canvas does not have a particular function Weon like a rectangle to create a circle, but we implement the arc function, and create a circle on the canvas. Let’s go through the code below and try to understand better using this example, 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <canvas id="canvas" width="400" height="300" style="border: 2px solid black;">
    
    </canvas>
</body>

<script>
    window.onload = function() {
    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
    context.arc(190, 150, 90, 0, 2 * Math.PI, false);
    context.stroke();
    };
</script>
</html>

 

OUTPUT

 

To draw a gradient using the HTML canvas element.

To draw a gradient in the HTML element, we can use the createLineargradient() method to draw gradients of our choice inside the canvas element. If we want to get the colorful gradient, we can use this method along with the addColorStop(), which would help to denote the gradient colors. If you wish to attain a more radial gradient, we have another method to save you: the createRadialGradient(). This method would make the color disposal more circular than linear. 

 

→ createLinearGradient(x,y,x1,y1) - creates a linear gradient

Here, the (x,y) and (x1,y1) define the coordinates of two points that specify the linear element’s position.

 

 

→ createRadialGradient(x,y,r,x1,y1,r1) - creates a radial/circular gradient

Here the (x,y) and(x1,y1) also define the coordinates of the two different points, but the r1 and r2 define the radial coordinates, which gives us a circular effect on the gradient. 

 

Let’s consider the below code as an example to understand both of the gradients better, 

 

  • Linear Gradient:


     
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <canvas id="canvas" width="400" height="300" style="border: 2px solid black;">
    </canvas>
</body>

<script>
    window.onload = function() {
        var c = document.getElementById("canvas");
        var ctx = c.getContext("2d");
        var gradient = ctx.createLinearGradient(0,0,300,0);
        gradient.addColorStop(0,"lightblue");
        gradient.addColorStop(1,"lightpink");
        ctx.fillStyle = gradient;
        ctx.fillRect(20,20,300,150);
    };
</script>
</html>

 

OUTPUT
 

 

  • Radial Gradient:


     
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <canvas id="canvas" width="400" height="300" style="border: 2px solid black;"></canvas>
</body>

<script>
    window.onload = function() {
        var c = document.getElementById("canvas");
        var ctx = c.getContext("2d");
        var gradient = ctx.createRadialGradient(80,50,10,100,20,90);
        gradient.addColorStop(0,"lightblue");
        gradient.addColorStop(1,"lightpink");
        ctx.fillStyle = gradient;
        ctx.fillRect(20,20,300,150);
    };
</script>
</html>

 

OUTPUT
 

 

 

These were a few designs we could create using the HTML canvas element. You can use these basic designs and try to make something more attractive on the canvas element. 

 

Frequently Asked Questions

 

  1. What is the HTML canvas element used for?

    Ans: The <canvas> element in HTML is used to draw graphics images using the scripting language Javascript. We can draw graphs, 2D shapes, render texts, combine photos and even integrate basic animations using Javascript. 


     
  2. What is the difference between SVG and the Canvas element?

    Ans:
    → SVG(Scalar Vector Graphics), as the name suggests SVG is composed of various shapes, whereas the Canvas element is based on Raster that means it is composed of pixels. 
    → SVG can be modified using both the scripting language and the CSS, but the Canvas element can only be modified using the scripting language. 
    → SVG is faster for rendering significant elements but slower for generating many elements as a group than canvas. 

     
  3. How can you create a simple shape on canvas?

    Ans: We can create a simple rectangle using the fillRect(), rect() and stroke() methods. The rect() method is used to define a rectangle image on the canvas, fillRect() is used to define a rectangle filled with a color property, and the stroke() method is used to draw the rectangle on the canvas. Using these methods, you can create a simple rectangle drawing on the canvas.


     

 

Key Takeaways

This article has covered all the essential properties you need to know about the canvas element. The canvas element is used to draw the graphs, implement game graphics and render basic 2D shapes and animations on our web pages using standard Javascript. You would be amazed to know that even though SVG graphics are faster than the HTML canvas element, the game graphics are still rendered better in our canvas element. There are various properties associated with the canvas element. We have helped you understand the basics and provided you with a guide to create simple 2D shapes, but do not limit yourself to just this Ninja. There is still a lot you can try using the HTML canvas. So are you ready to create amazing new animations using the properties and designs we have learned about? We have provided a fantastic Web Development course for you, and we feel it could be the perfect aid to make you better than the rest of the developers.  


Happy Learning Ninjas!
 

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think