The <canvas> element in HTML is used to draw graphics on a
web page via scripting (usually JavaScript). It's a powerful tool
for creating dynamic, scriptable rendering of 2D shapes and
bitmap images.
🔹 Basic Syntax
html
CopyEdit
<canvas id="myCanvas" width="400" height="300"></canvas>
This creates a blank area on the page where you can draw using
JavaScript.
🔹 Accessing the Canvas with JavaScript
javascript
CopyEdit
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d"); // "2d" is for 2D rendering
context
🔹 Drawing Examples
1. Draw a Rectangle
javascript
CopyEdit
ctx.fillStyle = "blue";
ctx.fillRect(50, 50, 100, 75); // x, y, width, height
2. Draw a Circle
javascript
CopyEdit
ctx.beginPath();
ctx.arc(150, 100, 40, 0, 2 * Math.PI); // x, y, radius, startAngle,
endAngle
ctx.fillStyle = "red";
ctx.fill();
ctx.stroke(); // optional: draw the circle's border
3. Draw Text
javascript
CopyEdit
ctx.font = "20px Arial";
ctx.fillStyle = "green";
ctx.fillText("Hello Canvas", 100, 200);
4. Draw a Line
javascript
CopyEdit
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(200, 100);
ctx.strokeStyle = "black";
ctx.stroke();
🔹 Common Uses of <canvas>
Drawing graphs and charts
Making simple games
Animations and visual effects
Real-time data visualizations
Photo and image editing