HTML Canvas

The html canvas element in HTML is a powerful tool that allows you to create and draw graphics, animations, and various other visual objects directly in your web pages. It's widely used for tasks like rendering charts, creating interactive games, and designing custom visual effects. Understanding how to use the HTML canvas is key to unlocking these advanced features.

In this chapter, we will explore the basics and move toward advanced usage of the <canvas> element, providing examples with thorough explanations and output demonstrations.

Introduction

The HTML <canvas> element is an empty drawing surface. By itself, it doesn’t draw anything. It works in conjunction with JavaScript to render graphics. The <canvas> element is part of the HTML5 specification and has quickly become an essential part of modern web development.

Key Features:

  • Can be used to draw basic shapes such as rectangles, circles, and lines.
  • Allows image manipulation and animation.
  • Supports both 2D and 3D drawing (though 3D is more complex and typically requires WebGL).

Example

				
					<canvas id="myCanvas" width="400" height="400"></canvas>

				
			

In the example above, we define a canvas element with an id of myCanvas and dimensions of 400×400 pixels. However, this alone won’t display anything on the page until we use JavaScript to draw on it.

Basic Structure of Canvas

A canvas element is defined with two main attributes: width and height. The content inside the canvas tag is displayed if the browser does not support the canvas element.

				
					<canvas id="basicCanvas" width="500" height="500">
  Your browser does not support the canvas element.
</canvas>

				
			

You can control the size of the canvas via the width and height attributes directly within the tag, or through CSS. However, it is recommended to define these properties using attributes for better clarity.

Working with the 2D Drawing Context

The real magic happens when you link the canvas element to JavaScript. To draw on the canvas, you need to use JavaScript to access the canvas’s 2D context, which provides all the drawing functions.

				
					<canvas id="myCanvas" width="400" height="400"></canvas> <script type="litespeed/javascript">const canvas=document.getElementById("myCanvas");const ctx=canvas.getContext("2d")</script> 
				
			

In this example, ctx refers to the 2D drawing context. All drawing functions are called through this context.

Drawing Shapes on the Canvas

Drawing Rectangles

You can draw rectangles using methods like fillRect, strokeRect, and clearRect.

				
					const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

// Draw a filled rectangle
ctx.fillStyle = "blue";
ctx.fillRect(50, 50, 200, 100);

				
			

Explanation

  • fillRect(x, y, width, height) draws a filled rectangle starting at the position (x, y) with the specified width and height.
  • ctx.fillStyle is used to set the color for the rectangle.

Output

A blue rectangle will appear on the canvas.

Drawing Circles (Arcs)

You can draw arcs or circles using the arc() method.

				
					ctx.beginPath();
ctx.arc(200, 200, 50, 0, 2 * Math.PI);
ctx.fillStyle = "red";
ctx.fill();

				
			
  • arc(x, y, radius, startAngle, endAngle) is used to draw circles or portions of circles.
  • The fill() method fills the shape with the specified color.

Output: A red circle is drawn on the canvas.

Working with Colors and Styles

Changing Fill and Stroke Colors

You can set the fill or stroke color for shapes using ctx.fillStyle or ctx.strokeStyle.

				
					ctx.fillStyle = "green";
ctx.fillRect(10, 10, 150, 100);

ctx.strokeStyle = "purple";
ctx.strokeRect(170, 10, 150, 100);

				
			

Explanation

  • fillStyle changes the fill color of a shape.
  • strokeStyle changes the outline color.

Output: A green filled rectangle and a purple outlined rectangle will appear.

Handling Text in Canvas

Text can also be rendered on the canvas using the fillText and strokeText methods.

				
					ctx.font = "30px Arial";
ctx.fillStyle = "black";
ctx.fillText("Hello Canvas", 50, 300);

				
			

Explanation

  • font sets the font size and type.
  • fillText() writes text at the specified coordinates (x, y).

Output: The text “Hello Canvas” will be displayed in black on the canvas.

Images and Canvas

You can also draw images onto the canvas using the drawImage() method.

				
					const img = new Image();
img.src = "image.png";
img.onload = function () {
  ctx.drawImage(img, 10, 10);
};

				
			

Explanation

  • This code loads an image from the source image.png and draws it at the position (10, 10) once it’s fully loaded.

Creating Animations

Animations can be achieved by continuously updating the canvas in a loop. The requestAnimationFrame() function is typically used to perform smooth animations.

				
					let x = 0;
function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "blue";
  ctx.fillRect(x, 50, 50, 50);
  x += 1;
  requestAnimationFrame(draw);
}
draw();

				
			

Explanation

  • clearRect() clears the canvas.
  • The square moves by increasing x in each frame, giving the illusion of motion.

Advanced Techniques: Transformations and Gradients

Transformations

Transformations like scaling, rotating, and translating objects can be done using methods such as rotate(), scale(), and translate().

Gradients

Gradients can add style to your shapes. You can create linear or radial gradients.

				
					const gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, "blue");
gradient.addColorStop(1, "green");

ctx.fillStyle = gradient;
ctx.fillRect(10, 10, 200, 100);

				
			

Output: A rectangle with a blue to green gradient fill will appear.

The canvas element opens up endless possibilities for rendering graphics, images, and animations in HTML. With the ability to combine shapes, text, images, and animations, it's a powerful tool for creating rich visual experiences on the web. By mastering the basics of shapes, colors, text, and transformations, along with more advanced techniques like animations and gradients, you can leverage the full power of HTML canvas for various applications. Happy coding !❤️

Table of Contents