🎨 Canvas API = Drawing Power
Need to draw graphics? Canvas API creates 2D graphics. Draw, animate, create games.
📝 Canvas Basics
<canvas id="myCanvas" width="400" height="200"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Rectangle
ctx.fillStyle = '#3498db';
ctx.fillRect(10, 10, 100, 50);
// Circle
ctx.beginPath();
ctx.arc(200, 75, 40, 0, Math.PI * 2);
ctx.fillStyle = '#e74c3c';
ctx.fill();
// Line
ctx.beginPath();
ctx.moveTo(10, 100);
ctx.lineTo(300, 50);
ctx.strokeStyle = '#2ecc71';
ctx.lineWidth = 5;
ctx.stroke();
// Text
ctx.font = '24px Arial';
ctx.fillStyle = '#333';
ctx.fillText('Hello Canvas', 50, 150);
</script>
🎯 Drawing Techniques
// Basic shapes
ctx.fillRect(x, y, width, height);
ctx.strokeRect(x, y, width, height);
ctx.clearRect(x, y, width, height);
// Paths
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x, y);
ctx.arc(x, y, radius, startAngle, endAngle);
ctx.closePath();
// Styles
ctx.fillStyle = 'color';
ctx.strokeStyle = 'color';
ctx.lineWidth = number;
ctx.font = 'size font-family';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
// Gradients
const gradient = ctx.createLinearGradient(x1, y1, x2, y2);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'blue');
ctx.fillStyle = gradient;
// Images
const img = new Image();
img.onload = () => {
ctx.drawImage(img, x, y, width, height);
};
img.src = 'image.png';
// Animation
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw frame
requestAnimationFrame(animate);
}
animate();
💡 Canvas Tips
- Use requestAnimationFrame for animations
- Clear canvas before each frame
- Use offscreen canvas for complex drawings
- Save and restore context states
- Use image objects for sprites
“Canvas API draws 2D graphics. Draw, animate, create games. Essential for creative web.”

