🎨 Drawing A Square Using Canvas: HTML, CSS and JavaScript

🧱 The Code
<!DOCTYPE html>
<html>
<head>
<title>Square Drawing</title>
</head>
<body>
<canvas id="canvas" width="400" height="400" style="border:1px solid black;"></canvas>
<script>
const ctx = document.getElementById("canvas").getContext("2d");
ctx.beginPath(); // Start drawing
ctx.moveTo(50, 50); // Start point
ctx.lineTo(150, 50); // Top edge
ctx.lineTo(150, 150); // Right edge
ctx.lineTo(50, 150); // Bottom edge
ctx.lineTo(50, 50); // Left edge (back to start)
ctx.strokeStyle = "red";
ctx.lineWidth = 4;
ctx.stroke(); // Draw the square
</script>
</body>
</html>
🧭 Line-by-Line Explanation — A Friendly Walkthrough
This simple program draws a red 100×100 square inside a 400×400 canvas. Let’s walk through it together.
<!DOCTYPE html>
Tells the browser this is an HTML5 page.
<html>
The container for everything on the page.
<head>
Holds metadata like the title.
<title>Square Drawing</title>
Sets the page title visible on the browser tab.
<body>
The visible part of the web page.
<canvas id="canvas" width="400" height="400" style="border:1px solid black;"></canvas>
Creates the drawing area.
Think of it like a blank board where we’ll sketch our square.
- The id allows JavaScript to find it.
- The width and height define its size.
- The border makes it visible.
<script>
Now we begin our drawing instructions.
const ctx = document.getElementById("canvas").getContext("2d");
Find the canvas and grab its “2D drawing tool.”
ctx.beginPath();
Start a new path — like saying “get a new page.”
ctx.moveTo(50, 50);
Move the pen to the first corner (top-left of our square).
ctx.lineTo(150, 50); → ctx.lineTo(150, 150); → ctx.lineTo(50, 150); → ctx.lineTo(50, 50);
These draw the four sides of the square.
ctx.strokeStyle = "red";
Make the square’s outline red.
ctx.lineWidth = 4;
Make the lines thicker — 4 pixels wide.
ctx.stroke();
Now tell the browser to “go ahead and draw it!”
🎯 Summary
Canvas gives you a pixel playground right inside the browser — perfect for games, drawings, charts, and animations. You move, line, color, and stroke — just like sketching with a digital pen.
✍️ Review Fill-Gap Questions
- The
<canvas>element provides a ____ grid where JavaScript can draw. - The top-left corner of the canvas is coordinate ____.
- The command
ctx.moveTo(50, 50)moves the pen ____ drawing a line. - The
lineTo()method adds a line from the ____ point to a new coordinate. - To actually display the shape on the screen, we call
ctx.________(). - The property used to set the outline color is
ctx.________. - The line thickness is controlled by
ctx.________. - The command
ctx.beginPath()starts a new ____ for drawing. document.getElementById("canvas")finds the canvas using its ____.- The square drawn in this code is ____ pixels wide and tall.