HTML Canvas


The HTML <canvas> element is used to draw graphics on a web page using JavaScript. It can be used to render shapes, graphs, game visuals, animations, and more.

🔹 By itself, <canvas> is just a container — the actual drawing is done using JavaScript.


🔹 Basic Syntax

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #000000;">
  Your browser does not support the canvas tag.
</canvas>

If the browser doesn't support <canvas>, the fallback text inside the tag is shown.


🔹 Getting the Drawing Context

To draw on the canvas, you need to access its 2D drawing context in JavaScript:

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

🔹 Drawing on the Canvas

✅ Draw a Line
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();

✅ Draw a Rectangle
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 150, 100);  // x, y, width, height

✅ Draw a Circle
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI); // x, y, radius, startAngle, endAngle
ctx.stroke();

✅ Write Text
ctx.font = "20px Arial";
ctx.fillText("Hello Canvas", 50, 50); // text, x, y

✅ Draw Image
const img = new Image();
img.onload = function () {
  ctx.drawImage(img, 0, 0);
};
img.src = "image.jpg";

Practice Questions

Q1. Create a <canvas> element of size 400x200 with a border.

Q2. Draw a horizontal line from (10,10) to (200,10).

Q3. Fill a blue rectangle from (30,30) with width=100, height=50.

Q4. Draw a circle with radius 40 at the center (100,100).

Q5. Display the text "Canvas Rocks!" on canvas at position (50,80).

Q6. Use JavaScript to change the fill color to green.

Q7. Load and draw an image onto the canvas.

Q8. Create a triangle using lineTo() method.

Q9. Draw two overlapping rectangles with different colors.

Q10. Use canvas to simulate a basic graph bar or grid.


Go Back Top