-
Hajipur, Bihar, 844101
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.
<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.
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");
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 150, 100); // x, y, width, height
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI); // x, y, radius, startAngle, endAngle
ctx.stroke();
ctx.font = "20px Arial";
ctx.fillText("Hello Canvas", 50, 50); // text, x, y
const img = new Image();
img.onload = function () {
ctx.drawImage(img, 0, 0);
};
img.src = "image.jpg";
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.
Q1: What is the purpose of <canvas> in HTML?
Q2: Which JavaScript method gets the 2D drawing context of a canvas?
Q3: What does ctx.beginPath() do?
Q4: How do you draw a filled rectangle?
Q5: Which method is used to write text on canvas?
Q6: What does ctx.stroke() do?
Q7: What does ctx.arc() draw?
Q8: Which HTML tag is used to define a canvas?
Q9: What happens if the browser does not support canvas?
Q10: What is the use of ctx.drawImage()?