Skip to main content
HTML for Beginners
CHAPTER 15 Beginner

HTML Canvas Basics

Updated: May 10, 2026
5 min read

# HTML Canvas Basics

1. Introduction

The <canvas> element is a blank drawing board inside your HTML page. By itself, it does nothing. But when combined with JavaScript, you can use it to draw graphics, render text, build charts, or even create 2D and 3D video games!

2. Learning Objectives

  • Define a <canvas> element.
  • Access the Canvas Context via JavaScript.
  • Draw basic shapes (rectangles, paths).

3. Detailed Explanations

Setting up the Canvas

You define the canvas in HTML, giving it an ID, a width, and a height.
html
1
<canvas id="myCanvas" width="400" height="200" style="border:1px solid #000;"></canvas>

Drawing with JavaScript

To draw on the canvas, you must get the "2D context" using JavaScript.
html
1234567891011
<script>
    // 1. Find the canvas
    var c = document.getElementById("myCanvas");
    
    // 2. Get the context (the drawing tool)
    var ctx = c.getContext("2d");

    // 3. Draw a filled rectangle
    ctx.fillStyle = "#FF0000"; // Red
    ctx.fillRect(0, 0, 150, 75); // x, y, width, height
</script>

Drawing Lines

You can draw paths by telling the "pen" where to move and where to draw a line.
javascript
1234
// Start a path
ctx.moveTo(0, 0); // Start at top left
ctx.lineTo(200, 100); // Draw line to middle
ctx.stroke(); // Actually render the ink

Drawing Text

Canvas can also render text directly onto the pixel grid.
javascript
12
ctx.font = "30px Arial";
ctx.fillText("Hello Canvas", 10, 50); // text, x, y

4. Mini Project: Simple Drawing App Foundation

Here is how you would set up a canvas to act like MS Paint.
html
1234567891011121314151617
<canvas id="paintCanvas" width="500" height="500" style="border: 2px solid black; cursor: crosshair;"></canvas>

<script>
    const canvas = document.getElementById(&#039;paintCanvas');
    const ctx = canvas.getContext(&#039;2d');
    
    // Simple demonstration of drawing a circle where a user might click
    function drawCircle(x, y) {
        ctx.beginPath();
        ctx.arc(x, y, 20, 0, 2 * Math.PI); // x, y, radius, startAngle, endAngle
        ctx.fillStyle = "blue";
        ctx.fill();
    }
    
    // Draw a test circle in the center
    drawCircle(250, 250);
</script>

5. MCQs

Q1: The HTML <canvas> element is used to draw graphics on a web page using...? A) CSS B) JavaScript C) SVG D) PHP *Answer: B*

6. Summary

The <canvas> tag is a portal into the world of browser-based rendering. While HTML defines the canvas boundary, the actual drawing (games, charts, visualizers) is done via the JavaScript Context API.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·