HTML Canvas
Draw graphics and animations with JavaScript
🎨 What is HTML Canvas?
The HTML Canvas element is used to draw graphics on a web page using JavaScript. It's like a blank drawing board where you can create shapes, text, images, and animations.
<!-- Basic canvas element -->
<canvas id="myCanvas" width="200" height="100"></canvas>
Output:
Canvas Basics
Drawing Context
Get 2D drawing context to draw
const ctx = canvas.getContext('2d');
Shapes
Draw rectangles, circles, lines
ctx.fillRect(10, 10, 50, 30);
Colors
Set fill and stroke colors
ctx.fillStyle = 'red';
Text
Add text to your canvas
ctx.fillText('Hello', 10, 30);
🔹 Drawing a Rectangle
Let's draw a simple colored rectangle:
<canvas id="rectCanvas" width="200" height="100"></canvas>
<script>
const canvas = document.getElementById('rectCanvas');
const ctx = canvas.getContext('2d');
// Set fill color to blue
ctx.fillStyle = 'blue';
// Draw a rectangle (x, y, width, height)
ctx.fillRect(20, 20, 60, 40);
</script>
Output:
🔹 Drawing a Circle
Create circles using the arc method:
<canvas id="circleCanvas" width="200" height="100"></canvas>
<script>
const canvas = document.getElementById('circleCanvas');
const ctx = canvas.getContext('2d');
// Begin a new path
ctx.beginPath();
// Draw a circle (x, y, radius, startAngle, endAngle)
ctx.arc(100, 50, 30, 0, 2 * Math.PI);
ctx.fillStyle = 'green';
ctx.fill();
</script>
Output:
🔹 Adding Text
Draw text on the canvas:
<canvas id="textCanvas" width="200" height="100"></canvas>
<script>
const canvas = document.getElementById('textCanvas');
const ctx = canvas.getContext('2d');
// Set font and color
ctx.font = '20px Arial';
ctx.fillStyle = 'purple';
// Draw text (text, x, y)
ctx.fillText('Hello Canvas!', 10, 40);
</script>