What is the Canvas?
<canvas>) that allows for dynamic, scriptable rendering of 2D shapes and bitmap images.Setting up the Canvas
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Canvas Basics</title>
<style>
canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="500" height="400"></canvas>
<script src="index.js"></script>
</body>
</html>
width and height can be controlled via attributes or CSS.300 x 150 if not specified.Drawing Context
The Canvas element alone cannot do anything. We must get a 2D drawing context from it in JavaScript:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
Rectangles
fillRect(x, y, width, height) - draws a filled rectangle.strokeRect(x, y, width, height) - draws a rectangle outline.clearRect(x, y, width, height) - erases the specified rectangular area.ctx.fillStyle = 'blue';
ctx.fillRect(10, 10, 100, 50);
ctx.strokeStyle = 'red';
ctx.strokeRect(150, 10, 100, 50);
ctx.clearRect(160, 20, 20, 20); // Clears a small 20x20 area
Coordinate System
x increases to the right, y increases downward.strokeRect) of a different color.clearRect to erase a small area from one of the rectangles.This will help you get comfortable with the basics of the canvas context and coordinate system.
beginPath(), closePath()
Allows you to start and end custom paths.
Example:
ctx.beginPath();
ctx.moveTo(50, 50); // Start at (50, 50)
ctx.lineTo(150, 50); // Line to (150, 50)
ctx.lineTo(100, 100); // Line to (100, 100)
ctx.closePath(); // Automatically draws a line back to (50, 50)
ctx.fillStyle = 'green';
ctx.fill();
Arc and Circle
ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise)ctx.beginPath();
ctx.arc(200, 200, 50, 0, Math.PI * 2, false);
ctx.fillStyle = 'orange';
ctx.fill();