The <canvas> element provides a drawing surface where you can create graphics, animations, and visualizations using JavaScript. It's perfect for games, charts, image editing, and dynamic graphics.
Basic Canvas Setup
Canvas is an HTML element with width and height attributes. Drawing is done with JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas Example</title>
<style>
canvas {
border: 1px solid #ccc;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="400" height="300"></canvas>
<script>
// Get canvas and context
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Draw a rectangle
ctx.fillStyle = '#4CAF50';
ctx.fillRect(50, 50, 200, 100);
</script>
</body>
</html>Drawing Shapes
Rectangles
<canvas id="canvas" width="400" height="300"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Filled rectangle
ctx.fillStyle = '#2196F3';
ctx.fillRect(20, 20, 150, 100);
// Stroked rectangle (outline only)
ctx.strokeStyle = '#f44336';
ctx.lineWidth = 3;
ctx.strokeRect(200, 20, 150, 100);
// Clear rectangle (erase area)
ctx.clearRect(50, 50, 50, 40);
</script>Circles and Arcs
<canvas id="canvas" width="400" height="300"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Draw a circle
ctx.beginPath();
ctx.arc(100, 100, 50, 0, 2 * Math.PI);
ctx.fillStyle = '#FF5722';
ctx.fill();
// Draw a circle outline
ctx.beginPath();
ctx.arc(250, 100, 50, 0, 2 * Math.PI);
ctx.strokeStyle = '#9C27B0';
ctx.lineWidth = 3;
ctx.stroke();
</script>Lines
<canvas id="canvas" width="400" height="300"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Draw a line
ctx.beginPath();
ctx.moveTo(50, 50); // Starting point
ctx.lineTo(350, 250); // Ending point
ctx.strokeStyle = '#4CAF50';
ctx.lineWidth = 5;
ctx.stroke();
// Draw multiple lines
ctx.beginPath();
ctx.moveTo(50, 250);
ctx.lineTo(200, 100);
ctx.lineTo(350, 250);
ctx.strokeStyle = '#2196F3';
ctx.stroke();
</script>Drawing Text
<canvas id="canvas" width="400" height="300"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Filled text
ctx.font = '40px Arial';
ctx.fillStyle = '#333';
ctx.fillText('Hello Canvas!', 50, 100);
// Stroked text
ctx.font = 'bold 30px Arial';
ctx.strokeStyle = '#2196F3';
ctx.lineWidth = 2;
ctx.strokeText('Outlined Text', 50, 200);
</script>Colors and Gradients
Linear Gradients
<canvas id="canvas" width="400" height="300"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Create linear gradient
const gradient = ctx.createLinearGradient(0, 0, 400, 0);
gradient.addColorStop(0, '#FF6B6B');
gradient.addColorStop(0.5, '#4ECDC4');
gradient.addColorStop(1, '#45B7D1');
// Use gradient
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 400, 300);
</script>Drawing Images
<canvas id="canvas" width="400" height="300"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Load image
const img = new Image();
img.onload = function() {
// Draw image at position (50, 50)
ctx.drawImage(img, 50, 50);
// Draw scaled image
ctx.drawImage(img, 50, 150, 100, 100);
};
img.src = 'image.jpg';
</script>Simple Animation
<canvas id="canvas" width="400" height="300"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let x = 0;
function draw() {
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw moving circle
ctx.beginPath();
ctx.arc(x, 150, 30, 0, 2 * Math.PI);
ctx.fillStyle = '#4CAF50';
ctx.fill();
// Update position
x += 2;
if (x > canvas.width) x = 0;
// Continue animation
requestAnimationFrame(draw);
}
draw();
</script>Interactive Canvas
<canvas id="canvas" width="400" height="300"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Draw on mouse click
canvas.addEventListener('click', function(e) {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
// Draw circle at click position
ctx.beginPath();
ctx.arc(x, y, 20, 0, 2 * Math.PI);
ctx.fillStyle = '#' + Math.floor(Math.random()*16777215).toString(16);
ctx.fill();
});
</script>Practical Example: Simple Chart
<canvas id="chart" width="400" height="300"></canvas>
<script>
const canvas = document.getElementById('chart');
const ctx = canvas.getContext('2d');
const data = [65, 85, 45, 90, 70];
const barWidth = 60;
const gap = 20;
data.forEach((value, index) => {
const x = gap + index * (barWidth + gap);
const height = value * 2;
const y = canvas.height - height - 30;
// Draw bar
ctx.fillStyle = '#2196F3';
ctx.fillRect(x, y, barWidth, height);
// Draw value
ctx.fillStyle = '#333';
ctx.font = '14px Arial';
ctx.fillText(value, x + 20, y - 5);
});
// Draw title
ctx.font = 'bold 20px Arial';
ctx.fillText('Sales Data', 10, 25);
</script>Best Practices
Set Canvas Dimensions in HTML
<!-- Good: Set in HTML attributes -->
<canvas id="canvas" width="800" height="600"></canvas>
<!-- Avoid: Setting via CSS only (causes scaling issues) -->
<canvas id="canvas" style="width: 800px; height: 600px;"></canvas>Provide Fallback Content
<canvas id="canvas" width="400" height="300">
Your browser doesn't support Canvas.
Please upgrade to a modern browser.
</canvas>Clear Before Redrawing
<script>
function animate() {
// Always clear before drawing new frame
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw new frame
// ...
requestAnimationFrame(animate);
}
</script>Common Uses for Canvas
- Games and interactive graphics
- Data visualizations and charts
- Image editing and filters
- Animations and effects
- Drawing applications
- Generative art
Key Takeaways
- Canvas provides a drawing surface for graphics
- Use JavaScript to draw shapes, text, and images
- Get context with
getContext('2d') - Set width/height in HTML, not CSS
- Clear canvas before redrawing in animations
- Use
requestAnimationFramefor smooth animations - Canvas is perfect for dynamic graphics and games
- Provide fallback content for older browsers
What's Next?
Now that you understand the Canvas element, the next lesson will cover SVG in HTML—another way to create graphics that's perfect for scalable, resolution-independent images and icons.