HTML <canvas> Tag โ Drawing Graphics
๐ Introduction
The <canvas> tag is used to draw graphics using JavaScript.
It does not display content by itselfโit creates a blank drawing area where you can render:
- Shapes
- Lines
- Images
- Animations
- Games
๐งฑ Syntax
<canvas id="myCanvas" width="300" height="150"></canvas>
๐ก Basic Example
<!DOCTYPE html>
<html>
<head>
<title>Canvas Example</title>
</head>
<body>
<canvas
id="myCanvas"
width="300"
height="150"
style="border:1px solid black;"
></canvas>
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(50, 30, 150, 80);
</script>
</body>
</html>
๐ฅ๏ธ Output Explanation
- A blank rectangle (canvas) appears
- JavaScript draws a blue rectangle inside it
- Everything is rendered dynamically
๐ฏ How <canvas> Works
- HTML creates the drawing area
- JavaScript accesses it
- JavaScript draws shapes using commands
โ๏ธ Important Methods
1. Get Context
const ctx = canvas.getContext("2d");
โ This gives you drawing tools
2. Draw Rectangle
ctx.fillRect(50, 50, 100, 80);
โ Creates a filled rectangle
3. Change Color
ctx.fillStyle = "red";
โ Sets drawing color
๐จ Example: Drawing Shapes
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// Red square
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 80, 80);
// Blue square
ctx.fillStyle = "blue";
ctx.fillRect(120, 20, 80, 80);
</script>
๐ฏ When to Use <canvas>
Use it for:
- Games ๐ฎ
- Charts ๐
- Animations โจ
- Drawing apps ๐จ
- Image processing ๐ผ๏ธ
โ ๏ธ Important Notes
<canvas>has no content without JavaScript- It is resolution-dependent
- Everything must be drawn manually
๐ซ Common Mistakes
- Forgetting JavaScript โ
- Not setting width/height โ
- Thinking it works like
<img>โ
๐งช Mini Exercise
Create a page that:
Has a
<canvas>elementDraws:
- One red rectangle
- One blue rectangle
Changes colors using
fillStyle