HTML Canvas Tutorial

HTML Canvas Tutorial

6 mins readComment
Esha
Esha Gupta
Associate Senior Executive
Updated on Oct 13, 2024 21:31 IST

Have you ever wondered about the power of HTML Canvas in modern web development? HTML Canvas has absolutely changed the way we experience content on the web. Let's understand more!

HTML Canvas is an element in HTML5 that provides a space on a web page where you can draw graphics using JavaScript. It was introduced with HTML5 and allows for dynamic, scriptable drawing of 2D shapes and bitmap images.

Recommended online courses

Best-suited Web Development courses for you

Learn Web Development with these high-rated online courses

โ‚น75 K
6 months
โ‚น1.5 L
13 months
โ‚น8.5 K
3 months
โ‚น1 L
6 months
โ‚น14.35 K
1 week
โ‚น90 K
6 months
โ‚น60 K
90 hours
โ‚น3.18 L
3 months
โ‚น70.5 K
12 months

Table of Content

What is HTML Canvas

HTML Canvas is an HTML5 element represented by the <canvas> tag. It creates a fixed-size drawing surface on a web page that can be used to generate graphics instantly. These graphics range from simple lines and shapes to complex images and animations. The drawing and manipulation of these graphics are controlled entirely by JavaScript, which makes Canvas a powerful tool for dynamic and interactive web content.

For example


 
<!DOCTYPE html>
<html>
<head>
<title> Canvas Example </title>
</head>
<body>
<!-- Canvas Element -->
<canvas id="myCanvas" width="480" height="320">
Your browser does not support the HTML canvas tag.
</canvas>
<!-- JavaScript to draw on the Canvas -->
<script>
// Your JavaScript code will go here
</script>
</body>
</html>
Copy code

Letโ€™s Understand in Detail

In the example code written above, we have the following:

Canvas Element: <canvas id="myCanvas" width="480" height="320"></canvas>

  • id attribute is used to uniquely identify the canvas element.
  • width and height attributes specify the size of the canvas.

Fallback Content: Text inside the <canvas> tags (e.g., "Your browser does not support the HTML canvas tag.") is displayed if the browser does not support the <canvas> element.

JavaScript for Drawing: Inside the <script> tags, you can use JavaScript to draw on the canvas. 

For example


 
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
// Drawing a rectangle
ctx.fillStyle = 'green';
ctx.fillRect(10, 10, 150, 100); // Fill a rectangle with green color
Copy code

In this code snippet above we have:

  • getContext('2d') is used to get the 2D rendering context which is the actual tool we can use to paint on the Canvas.
  • fillStyle sets the color, gradient, or pattern used to fill the drawing.
  • fillRect(x, y, width, height) draws a filled rectangle.
 

Applications of HTML Canvas

  •  Canvas is used for 2D game development in web browsers. 
  •  It's commonly used for drawing charts, graphs, and other forms of data visualisation. 
  • Artists and designers can use canvas to create complex drawings, photo compositions, and artistic designs. It offers a wide range of functions to draw shapes, colors, and images.
  • Canvas can be used to build basic image editing tools directly in the browser. It allows for operations like cropping, resizing, filtering, and other image manipulations.
  • Custom UI elements like sliders, gauges, and progress bars can be created using canvas.
  •  Complex web-based tools like diagram editors, drawing tools, or even music production software can be developed using the canvas API.

Examples of HTML Canvas

Basic Drawing: Rectangle

Problem Statement: Create a simple web page that displays a blue rectangle on a canvas element. 


 
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"> </canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Set color and draw a rectangle
ctx.fillStyle = "blue";
ctx.fillRect(20, 20, 150, 50);
</script>
</body>
</html>
Copy code

Output

This code draws a simple blue rectangle on the canvas.

Animation: Moving Ball

Problem Statement: Develop an animation of a ball moving across the canvas, bouncing back when it reaches the edges.


 
<!DOCTYPE html>
<html>
<body>
<canvas id="ballCanvas" width="480" height="320" style="border:1px solid #000000;"> </canvas>
<script>
var canvas = document.getElementById("ballCanvas");
var ctx = canvas.getContext("2d");
var x = canvas.width / 2;
var y = canvas.height - 30;
var dx = 2;
var dy = -2;
var ballRadius = 10;
// Function to draw the ball
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
// Update the ball's position
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
x += dx;
y += dy;
}
setInterval(draw, 10); // Repeat draw function every 10ms
</script>
</body>
</html>
Copy code

Output

.

This code creates an animation of a blue ball moving across the canvas.

Interactive Drawing: Drawing with Mouse

Problem Statement: Implement a drawing application where users can draw freehand on the canvas using their mouse.


 
<!DOCTYPE html>
<html>
<body>
<canvas id="drawCanvas" width="480" height="320" style="border:1px solid #000000;"> </canvas>
<script>
var canvas = document.getElementById("drawCanvas");
var ctx = canvas.getContext("2d");
var painting = false;
// Start drawing on mouse down
canvas.addEventListener('mousedown', function(e) {
painting = true;
draw(e);
});
// Stop drawing on mouse up or leave canvas
canvas.addEventListener('mouseup', () = > painting = false);
canvas.addEventListener('mouseleave', () = > painting = false);
// Draw on canvas
function draw(e) {
if (!painting) return;
ctx.lineWidth = 5;
ctx.lineCap = 'round';
ctx.lineTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
}
canvas.addEventListener('mousemove', draw);
</script>
</body>
</html>
Copy code

Output

This canvas application allows the user to draw freehand with the mouse.

Chart Drawing: Simple Bar Chart

Problem Statement: Construct a simple bar chart on the canvas using predefined data values. 


 
<!DOCTYPE html>
<html>
<body>
<canvas id="chartCanvas" width="480" height="320" style="border:1px solid #000000;"> </canvas>
<script>
var canvas = document.getElementById("chartCanvas");
var ctx = canvas.getContext("2d");
var values = [10, 20, 30, 40, 50]; // Sample data values
var barWidth = 40;
var barSpacing = 10;
var xOffset = 30;
// Draw bars for each value
values.forEach(function(value, index) {
ctx.fillStyle = 'blue';
ctx.fillRect(xOffset + (barWidth + barSpacing) * index, canvas.height - value, barWidth, value);
});
</script>
</body>
</html>
Copy code

Output

This code draws a simple bar chart based on the provided data values.

These example shows different use cases of the HTML canvas, from basic drawing and animation to interactivity and data visualization.

Key Takeaways

  • The <canvas> element is extremely useful in web development. 
  • The canvas can be used for various purposes like game development, data visualization, artistic designs, image editing, custom UI elements, and even complex web-based tools.
  • Canvas supports user interaction, enabling the creation of applications where users can directly interact with the canvas through inputs like mouse clicks and movements.
  • The <canvas> tag supports fallback content, ensuring that a message is displayed if a user's browser doesn't support the canvas element.
  •  While Canvas is powerful, it's important to consider performance and optimization in order to ensure a smooth user experience.

FAQs

What is HTML Canvas?

HTML Canvas is a part of HTML5 that allows for dynamic, scriptable rendering of 2D shapes and bitmap images. It provides a drawing surface within a web page where graphics can be drawn on the fly using JavaScript.

How do you create a Canvas element in an HTML page?

To create a Canvas element, you simply add the <canvas> tag to your HTML document. You can specify its width and height attributes to set the size of the drawing area. 

Can the Canvas element be styled with CSS?

Yes, the Canvas element can be styled with CSS like any other HTML element. You can apply borders, background colors, and other CSS properties to the Canvas element to fit the design of your web page.

Is it possible to draw both 2D and 3D graphics with HTML Canvas?

Primarily, HTML Canvas is used for drawing 2D graphics using JavaScript. However, with the help of a library like WebGL, you can also draw 3D graphics on a Canvas.

How do you access the drawing context of a Canvas?

To draw on a Canvas, you first need to access its drawing context using JavaScript. For 2D graphics, you can get the context by calling the getContext("2d") method on the Canvas element. 

About the Author
author-image
Esha Gupta
Associate Senior Executive

Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio