HTML Canvas Tag

The <canvas> tag is used to create a drawing area where you can draw graphics using JavaScript. Think of it like a blank whiteboard or drawing pad placed on your webpage — you can sketch shapes, lines, graphs, charts, animations, and even games on it.

However, canvas by itself doesn’t draw anything. It's just an empty space. You’ll need JavaScript to actually do the drawing.

Why Use the <canvas> Tag?

You can use <canvas> when you want to:

  • Draw custom shapes like rectangles, circles, or lines.
  • Build interactive graphs, charts, or infographics.
  • Create animations or small games right on the browser.
  • Make image editing tools, dashboards, or visual effects.
Syntax -
<canvas id="myCanvas" width="300" height="150"></canvas>
AttributeDescriptionValues
id This helps you target the canvas using JavaScript. Name
width Specifies width in pixels. Number in pixels. Default value is 300.
height Specifies height in pixels. Number in pixels. Default value is 150.
Example -

Scenario - Example Using <canvas> Tag

<!DOCTYPE html>
<html>
	<head>
		<title> Canvas element example.. </title>
	</head>
	<body>
		<canvas id="myCanvas" width="300" height="200" 
				style="border:1px solid #000000;"></canvas>
		<script>
		  var canvas = document.getElementById("myCanvas");
		  var ctx = canvas.getContext("2d");

		  ctx.fillStyle = "tomato";
		  ctx.fillRect(40, 40, 100, 70);

		  ctx.fillStyle = "navy";
		  ctx.font = "20px Verdana";
		  ctx.fillText("Box!", 50, 100);
		</script>
	</body>
</html>
Output -
Explaining Example -

Try copying that into a .html file and open it in your browser. You'll see a simple box and text drawn using canvas.