📄
Canvas API
Advanced
120 XP
45 min
Lesson Content
HTML5 Canvas API
The Canvas API allows you to draw graphics, animations, and interactive content directly in the browser using JavaScript.
Canvas Element
The <canvas> element creates a drawing surface:
<canvas id="myCanvas" width="800" height="600">
Your browser does not support the canvas element.
</canvas>Getting the Context
To draw on canvas, you need to get the 2D rendering context:
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
</script>Basic Drawing
Rectangles:
// Filled rectangle
ctx.fillStyle = 'blue';
ctx.fillRect(10, 10, 100, 100);
// Outlined rectangle
ctx.strokeStyle = 'red';
ctx.strokeRect(120, 10, 100, 100);Paths and Lines:
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(150, 50);
ctx.lineTo(100, 150);
ctx.closePath();
ctx.stroke();Circles and Arcs:
ctx.beginPath();
ctx.arc(100, 100, 50, 0, 2 * Math.PI);
ctx.fill();Text on Canvas
ctx.font = '30px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello Canvas', 10, 50);Images on Canvas
const img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
};
img.src = 'image.jpg';Canvas Attributes
- width and height - Set canvas dimensions (in pixels)
- Always set dimensions via attributes, not CSS (CSS can distort the canvas)
Common Use Cases
- Data visualization and charts
- Games and animations
- Image editing and filters
- Interactive graphics
- Drawing applications
Best Practices
- Set canvas size using width and height attributes
- Always provide fallback content inside <canvas> tags
- Clear the canvas before redrawing (ctx.clearRect())
- Use requestAnimationFrame() for smooth animations
- Consider performance for complex drawings
Example Code
Create a canvas and draw a rectangle, circle, and some text.
<!DOCTYPE html>
<html>
<head>
<title>Canvas Drawing</title>
</head>
<body>
<!-- Create a canvas element with id="myCanvas", width="400", height="300" -->
<script>
// Get canvas and context
// Draw a blue filled rectangle at (10, 10) with width 100, height 80
// Draw a red circle (arc) at center (200, 150) with radius 50
// Draw text "Hello Canvas" at position (10, 200)
</script>
</body>
</html>Expected Output:
Canvas with shapes and text
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code