HTML Canvas API
ποΈ Introduction to the HTML Canvas API
The <canvas> element and its API allow you to draw graphics, animations, and visual effects dynamically using JavaScript. It provides a powerful way to create 2D shapes, images, charts, games, and more β all rendered directly in the browser. πΌοΈ
>>βWith Canvas, your imagination becomes pixels.β π¨
π What is the Canvas Element?
The HTML <canvas> tag defines a rectangular area on a webpage where you can draw graphics using JavaScript. It acts like a digital drawing board.
Basic Canvas Element
<canvas id="myCanvas" width="400" height="200"></canvas>βοΈ Accessing the Canvas Context
To draw on the canvas, you first get its 2D rendering context in JavaScript:
Get 2D Context
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');ποΈ Drawing Basic Shapes
Here are some simple examples to get you started:
Drawing a Rectangle
// Draw a filled rectangle
ctx.fillStyle = 'skyblue';
ctx.fillRect(50, 50, 150, 100);Drawing a Circle
// Draw a circle
ctx.beginPath();
ctx.arc(150, 125, 50, 0, Math.PI * 2);
ctx.fillStyle = 'tomato';
ctx.fill();
ctx.closePath();ποΈ Drawing Lines and Paths
Drawing Lines
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(200, 100);
ctx.strokeStyle = 'green';
ctx.lineWidth = 4;
ctx.stroke();
ctx.closePath();πΌοΈ Working with Images
You can also draw images on the canvas:
Drawing an Image
const img = new Image();
img.src = 'path/to/image.png';
img.onload = () => {
ctx.drawImage(img, 0, 0, 300, 150);
};ποΈ Creating Animations
Use JavaScript functions like requestAnimationFrame() to create smooth animations on canvas.
Basic Animation Example
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear canvas
ctx.fillStyle = 'blue';
ctx.fillRect(x, 50, 50, 50); // Draw moving square
x += 2;
if (x > canvas.width) x = -50;
requestAnimationFrame(animate);
}
animate();π§ Tips & Best Practices
- Always clear the canvas before redrawing during animations.
- Use layered canvases for complex effects.
- Keep performance in mind: limit heavy calculations inside animation loops.
- Test on different screen sizes and devices.
π Useful Resources
>>βCanvas lets you paint directly on the web β the possibilities are endless!β π¨