1. Home
HTML

Learn HTML: A Comprehensive Tutorial for Beginners | Step-by-Step Guide

Learn HTML from scratch! Our tutorial covers basics to advanced concepts. Start coding websites today with step-by-step guidance.

  • 49
  • 12 Hours
right-top-arrow
24

HTML Canvas

Updated on 06/08/2024456 Views

Imagine having a virtual drawing board right in your web browser where you can create incredible artwork, animations, and interactive games. That is exactly what HTML canvas aims to be! It's similar to a magical canvas where developers may use code to sketch, paint, animate, and bring creative ideas to life on a website.

In this HTML canvas tutorial, I will explore how HTML canvas works. I'll guide you on how to use this tool to draw shapes, add colors, produce animations, and develop interactive features. 

What is HTML Canvas?

Canvas is an HTML element that allows developers to dynamically create visuals, animations, and interactive content using JavaScript. It enables developers to create shapes, lines, text, photos, and other elements directly within a web browser. 

The element serves as a blank canvas for canvas HTML5 JavaScript to modify pixels and build visual elements, making it an effective tool for developing games, data visualizations, interactive charts, animations, and unique user interfaces for the web. We use the canvas tag in HTML to define this element. Let me show you an example to give you a better understanding.

Code:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title> HTML Canvas Example </title>

</head>

<body>

    <canvas id="myCanvas_example" width="200" height="100"></canvas>

    <script>

        // Get the canvas element which is myCanvas_example

        var canvas = document.getElementById("myCanvas_example");

        // Get the drawing context which is 2D

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

        // Drawing a rectangle

        ctx.fillStyle = "#FF8213"; // Orange color

        ctx.fillRect(10, 10, 150, 80); // x, y, width, height

    </script>

</body>

</html>

Now, let me dissect the above example to explain the program better.

  • We have a canvas element (<canvas>) with the ID "myCanvas_example" and a size of 200x100 pixels.
  • In the <script> tag, we utilize canvas HTML5 JavaScript to retrieve the canvas element and its 2D drawing context (getContext("2d")).
  • We then utilize the fillStyle attribute to make the fill color orange (#FF8213).
  • The fillRect() method is then used to create a filled rectangle at coordinates (10, 10) that is 150 pixels wide and 80 pixels tall.

HTML Canvas Examples

Let us now discuss different use cases of canvas using different examples one by one.

Line

First, let me start with how to draw a line in HTML canvas. I’ll explain with an example.

Code:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>HTML Canvas Line Example</title>

    <style>

        #myCanvas_line{

            border: 2px solid red;

        }

    </style>

</head>

<body>

    <canvas id="myCanvas_line" width="400" height="200"></canvas>

    <script>

        // Get the canvas element which is myCanvas_line

        var canvas = document.getElementById("myCanvas_line");

        // Get the drawing context (2D)

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

        // Set line style

        ctx.strokeStyle = "#AA00FF"; // Purple color

        ctx.lineWidth = 7; // 7 pixels wide

        // Draw a line

        ctx.beginPath();

        ctx.moveTo(50, 50); // Starting point (x, y)

        ctx.lineTo(350, 150); // Ending point (x, y)

        ctx.stroke(); // Draw the line

    </script>

</body>

</html>

Now, let me explain the above example.

  • We have a canvas element (<canvas>) with the ID "myCanvas_line" and a size of 400x200 pixels.
  • In the <script> tag, we utilize JavaScript to retrieve the canvas element and its 2D drawing context (getContext("2d")).
  • We set the line style to purple (#AA00FF) and the line width to 7 pixels.
  • The beginPath() method creates a new route for drawing.
  • Here, moveTo() function specifies the line's starting point at coordinates (50,50), and lineTo() function creates a line from the starting position to the terminating point at coordinates (350, 150).
  • Finally, stroke() is used to create a line with the desired style and width.

When you open this HTML file in a web browser, a purple line will appear on the canvas between points (50, 50) and (350, 150), as you can see in the above example.

Text

Now let me teach you how to add text using canvas in HTML with the help of an example.

Code:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>HTML Canvas Text Example</title>

    <style>

        #myCanvas_text{

            border: 2px solid blue;

        }

    </style>

</head>

<body>

    <canvas id="myCanvas_text" width="500" height="300"></canvas>

    <script>

        // Get the canvas element which is myCanvas_text

        var canvas = document.getElementById("myCanvas_text");

        // Get the drawing context (2D)

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

        // Set text style

        ctx.font = "30px Arial"; // Font size and type

        ctx.fillStyle = "#AA0000"; // Text color assigned to red

        // Write text you want to show

        ctx.fillText("HTML Canvas Text!", 150, 200); // Text, x, y

    </script>

</body>

</html>

Let’s dissect the above example.

  • We have a canvas element (<canvas>) with the ID "myCanvas_text" and a size of 500x300 pixels.
  • We use the font to select a 30px Arial font and fillStyle to provide a red text color.
  • The fillText() method is used to write "HTML Canvas Text!" at coordinates (150, 200) on the canvas.

As you can see in the output, the text "HTML Canvas Text!" will appear in red at the specified coordinates on the canvas. You can customize the font size, font type, text color, and position to the needs of the website you are creating.

Gradients

We can also apply a gradient effect to our canvas to make it more interesting. Let me demonstrate this with an example.

Code:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title> Example of HTML Canvas Gradient </title>

    <style>

        #myCanvas_gradient{

            border: 2px solid red;

        }

    </style>

</head>

<body>

    <canvas id="myCanvas_gradient" width="500" height="300"></canvas>

    <script>

        // Get the canvas element

        var canvas = document.getElementById("myCanvas_gradient");

        // Get the drawing context (2D)

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

        // Here we are Creating a linear gradient

        var gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);

        gradient.addColorStop(0, "lightgreen"); // Start color is lightgreen

        gradient.addColorStop(1, "blue"); // End color is blue

        // Here we are Filling the rectangle with gradient

        ctx.fillStyle = gradient;

        ctx.fillRect(0, 0, canvas.width, canvas.height);

    </script>

</body>

</html>

Let me explain the above program point by point.

  • We have a canvas element (<canvas>) with the ID "myCanvas_gradient" and a size of 500x300 pixels.
  • In the <script> tag, we are using JavaScript to retrieve the canvas element and its 2D drawing context with the help of getContext("2d").
  • We then built a linear gradient with createLinearGradient(x0, y0, x1, y1), where (x0, y0) is the gradient's starting point and (x1, y1) is its finishing point. In this example, the gradient begins at (0, 0) and ends at (canvas.width, 0), resulting in a horizontal gradient from left to right.
  • We then used addColorStop(offset, color) to add color stops to the gradient, where the offset is a number between 0 to 1 representing the point along the gradient, and color is the color at that position. Here, we put a light green color stop at 0 (beginning) and a blue color stop at 1 (ending).
  • Finally, we then used fillRect(x, y, width, height) to apply the linear gradient throughout the entire canvas.

When you use this example program on your own, you'll notice a horizontal gradient from light green to blue filling the canvas. Always remember, this is just an example and you can tweak all the properties as per your liking and needs of your program. You can further refine your skills by practicing different HTML projects.

Circle

Now, let me teach you how to draw a circle with the help of canvas in HTML.

Code:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title> Example of HTML Canvas Circle </title>

    <style>

        #myCanvas_circle{

            border: 2px solid blue;

        }

    </style>

</head>

<body>

    <canvas id="myCanvas_circle" width="500" height="300"></canvas>

    <script>

        // Get the canvas element which is myCanvas_circle in this program

        var canvas = document.getElementById("myCanvas_circle");

        // Get the drawing context (2D)

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

        // Setting up the circle properties

        var centerX = canvas.width / 2; // X-coordinate of circle center

        var centerY = canvas.height / 2; // Y-coordinate of circle center

        var radius = 60; // Circle radius

        var startAngle = 0; // Start angle (in radians)

        var endAngle = 2 * Math.PI; // End angle (in radians)

        var anticlockwise = false; // Direction of drawing (clockwise or anticlockwise)

        // Draw circle

        ctx.beginPath(); // Begin drawing path of the circle

        ctx.arc(centerX, centerY, radius, startAngle, endAngle, anticlockwise); // Draw arc of the circle

        ctx.fillStyle = "lightgreen"; // Circle fill color set to light green

        ctx.fill(); // Fill circle with color

        ctx.closePath(); // Close drawing path

    </script>

</body>

</html>

Let’s explain the above example.

  • We have a canvas element (<canvas>) with the ID "myCanvas_gradient" and size of 500x300 pixels.
  • We then defined the circle's attributes. In this case, they are the center coordinates (centerX and centerY), radius (radius), start and end angles (startAngle and endAngle), and drawing orientation (anticlockwise).
  • The circle is drawn using the ctx.arc() method, which specifies the center, radius, start and end angles, and drawing direction.
  • We use ctx.fillStyle to set the circle's fill color and then ctx.fill() to fill it with that color.

If you run this program, you will see a circle that is light green in color. You can change the attributes as per your wants.

In Conclusion

HTML Canvas is an effective tool for producing dynamic and interactive graphics on websites. From simple shapes and animations to complex graphics and game creation, the Canvas API opens up new creative possibilities for web developers and designers.

If you want to learn more about HTML elements, I would recommend checking out courses from upGrad. They offer some of the best-certified courses available in the industry.

Frequently Asked Questions

  1. What is HTML canvas used for?

The canvas element in HTML dynamically draws graphics, animations, and interactive information on a webpage using JavaScript. It provides a drawing surface that enables developers to create and manipulate graphical components, including lines, forms, text, images, and animations right in the browser.

  1. Is HTML canvas supported on all browsers?

Canvas is supported by almost all modern browsers, with the exception of a few very outdated versions.

  1. Can I use CSS with HTML canvas?

You can add CSS with canvas to style the container and add animations but you cannot use CSS to change the shapes and graphics in the canvas itself.

  1. Is HTML canvas suitable for complex graphics?

Canvas in HTML is an excellent choice for complex visuals, especially if you require fine-grained control, animation, and performance. However, the development process might be quite difficult.

  1. Are there any libraries or frameworks for HTML canvas?

Numerous tools and frameworks are available to make working with Canvas easier, particularly for complex visuals. Some of them include Three.js for 3D models and Anime.js for animation.

  1. What is canvas path in HTML?

In canvas, a path is a set of connected points that describe the shape you want to draw on the canvas. It's like a blueprint for your drawing. Paths are created using JavaScript techniques provided by the Canvas API.

  1. Is HTML canvas 2D or 3d?

Canvas is primarily for 2D graphics. It offers a useful API for drawing shapes, lines, text, and images on a webpage. While the canvas API does not directly create actual 3D visuals, there are techniques to achieve some 3D-like effects.

  1. Is HTML canvas suitable for creating printable graphics?

Canvas in HTML has various restrictions that make it unsuitable for producing high-quality printable graphics because of limited vector support and resolution dependence.

Rohan Vats

Rohan Vats

Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...