Canvas API (2D Graphics in JavaScript)
The Canvas API allows you to draw 2D graphics directly in the browser using JavaScript. It provides a drawing surface via the <canvas>
HTML element, which can be used for shapes, images, text, and animations.
Creating a Canvas
<canvas id="myCanvas" width="400" height="200" style="border:1px solid #000;"></canvas>
id
→ Used to reference the canvas in JavaScript.width
andheight
→ Set the size of the canvas (default 300x150).style
→ Optional, to show a border or other CSS styling.
Accessing the 2D Context
The 2D context provides all the methods to draw shapes and text.
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d"); // "2d" context for 2D graphics
Drawing Shapes
Rectangle
// Filled rectangle
ctx.fillStyle = "blue"; // Color
ctx.fillRect(20, 20, 150, 100);
// Rectangle outline
ctx.strokeStyle = "red";
ctx.strokeRect(200, 20, 150, 100);
// Clear rectangle
ctx.clearRect(50, 50, 50, 50); // Clears part of the canvas
Circle / Arc
ctx.beginPath(); // Start path
ctx.arc(100, 150, 50, 0, 2 * Math.PI); // x, y, radius, startAngle, endAngle
ctx.fillStyle = "green";
ctx.fill();
ctx.stroke(); // Outline
Drawing Text
ctx.font = "20px Arial";
ctx.fillStyle = "purple";
ctx.fillText("Hello Canvas!", 50, 50); // Draw filled text
ctx.strokeStyle = "black";
ctx.strokeText("Outlined Text", 50, 80); // Draw outline text
Drawing Images
const img = new Image();
img.src = "example.png";
img.onload = function() {
ctx.drawImage(img, 50, 50, 100, 100); // x, y, width, height
};
Animation Basics
requestAnimationFrame()
→ Smooth animation loop.- Always clear canvas before redrawing moving objects.
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear canvas
ctx.fillStyle = "blue";
ctx.fillRect(x, 50, 50, 50);
x += 2;
if(x < canvas.width) requestAnimationFrame(animate); // Loop
}
animate();
Styling Shapes
fillStyle
→ Fill colorstrokeStyle
→ Outline colorlineWidth
→ Outline thicknessglobalAlpha
→ Transparency