Skip to content

Introduction to HTML5 Canvas API | Lecture 40

Introduction to HTML5 Canvas

Let’s begin with Lecture 40 of the HTML5 & CSS3 series. Introduction to HTML5 Canvas API – Drawing with JavaScript. This lecture is for absolute beginners; even kids can follow along and understand.

🎯 Objective:

By the end of this lecture, you will:

  • Understand what the Canvas API is and how it works
  • Be able to draw basic shapes like lines, rectangles, and circles
  • Learn how to use colors, strokes, and fills
  • Create a simple drawing or animation using JavaScript
  • Make your website interactive and visual — not just text and buttons!

🎨 What Is the Canvas API?

The Canvas API lets you draw graphics directly in your browser using JavaScript.

Think of it like this:

If your webpage was a canvas for painting, then HTML5 Canvas is your digital art board — and JavaScript is your brush!

You can use it for:

  • Games
  • Charts and graphs
  • Simple animations
  • Interactive drawings
  • Visual effects

📐 How to Use the <canvas> Element

First, add the <canvas> tag to your HTML:

<canvas id="myCanvas" width="500" height="300"></canvas>

Then get access to it using JavaScript:

let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d"); // 2D drawing context

Now ctx is your paintbrush — time to draw!

🔧 Basic Canvas Methods
METHODDESCRIPTION
ctx.fillStyleSets the color used to fill shapes
ctx.strokeStyleSets the color used for borders
ctx.fillRect(x, y, width, height)Draws a filled rectangle
ctx.strokeRect(x, y, width, height)Draws an outlined rectangle
ctx.beginPath()Starts a new path
ctx.moveTo(x, y)Moves the drawing cursor
ctx.lineTo(x, y)Draws a line from current point
ctx.arc(x, y, radius, startAngle, endAngle)Draws a circle or arc
ctx.fill()Fills the current path
ctx.stroke()Outlines the current path
💻 Try This: Draw a Smiling Face on the Canvas

Let’s create a simple drawing of a smiling face using the Canvas API.

Step 1: Create a New File

In your VS Code project folder (MyFirstWebsite), create a new file named:

canvas-drawing.html
Step 2: Add This Code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Canvas Drawing</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 40px;
            text-align: center;
        }

        canvas {
            border: 1px solid #ccc;
            background-color: #fff;
        }
    </style>
</head>
<body>

    <h2>Smiling Face with Canvas</h2>

    <canvas id="myCanvas" width="300" height="300"></canvas>

    <p style="margin-top: 20px;">
        <a href="index.html">Back to Home</a>
    </p>

    <script>
        let canvas = document.getElementById("myCanvas");
        let ctx = canvas.getContext("2d");

        // Draw face
        ctx.beginPath();
        ctx.arc(150, 150, 80, 0, Math.PI * 2); // Full circle
        ctx.fillStyle = "#ffeb3b"; // Yellow
        ctx.fill();
        ctx.strokeStyle = "#333";
        ctx.stroke();

        // Left eye
        ctx.beginPath();
        ctx.arc(110, 120, 10, 0, Math.PI * 2);
        ctx.fillStyle = "black";
        ctx.fill();

        // Right eye
        ctx.beginPath();
        ctx.arc(190, 120, 10, 0, Math.PI * 2);
        ctx.fill();

        // Smile
        ctx.beginPath();
        ctx.arc(150, 150, 50, 0, Math.PI); // Half-circle
        ctx.lineWidth = 3;
        ctx.strokeStyle = "black";
        ctx.stroke();
    </script>

</body>
</html>
Step 3: Run with Live Server

Right-click the code → Show All Commands → Launch Live Server

🎉 You’ve drawn a smiling face using only HTML and JavaScript! It’s your first step into the world of web-based graphics.

Introduction to HTML5 Canvas
Introduction to HTML5 Canvas
💡 Bonus: Draw a Rainbow Line

Let’s make a colorful rainbow line across the canvas.

Add This Below Your Smile Code:
// Rainbow Line
ctx.beginPath();
ctx.moveTo(10, 250);

let colors = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"];

for (let i = 0; i < colors.length; i++) {
    ctx.strokeStyle = colors[i];
    ctx.lineWidth = 10;
    ctx.lineTo(60 + i * 50, 250);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(60 + i * 50, 250);
}

This draws a rainbow-colored line — one color at a time!

💡 Bonus: Animate a Bouncing Ball

Let’s bring your canvas to life with a bouncing ball animation .

Update Your Canvas Size:
<canvas id="myCanvas" width="500" height="300"></canvas>
Replace Your Script with This:
<script>
    let canvas = document.getElementById("myCanvas");
    let ctx = canvas.getContext("2d");

    let x = 100;
    let y = 100;
    let dx = 3;
    let dy = 2;
    let radius = 20;

    function drawBall() {
        ctx.beginPath();
        ctx.arc(x, y, radius, 0, Math.PI * 2);
        ctx.fillStyle = "#e74c3c";
        ctx.fill();
        ctx.closePath();
    }

    function animate() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // Move ball
        x += dx;
        y += dy;

        // Bounce off walls
        if (x + radius > canvas.width || x - radius < 0) {
            dx = -dx;
        }

        if (y + radius > canvas.height || y - radius < 0) {
            dy = -dy;
        }

        drawBall();
        requestAnimationFrame(animate);
    }

    animate(); // Start animation
</script>

🎉 Now there’s a red ball bouncing around your canvas — your first animated graphic!

🧪 Try It Yourself!

  1. Draw a house using rectangles and triangles.
  2. Create a color picker input that changes the ball color live.
  3. Add a click event that draws a dot where you click.
  4. Build a simple game like “Click the Ball” or “Catch the Falling Shapes”.
✅ Summary of What You Learned Today
CONCEPTDESCRIPTION
Canvas TagThe area where you draw graphics
Context (ctx)Your drawing tool inside the canvas
Drawing ShapesRectangles, arcs, lines, and paths
Colors & StylesfillStyle,strokeStyle,lineWidth
Animation LoopUserequestAnimationFrame()for smooth animation
Event InteractionDraw based on user clicks or mouse movement

🚀 Next Lecture Preview:

In Lecture 41 , we’ll explore more advanced Canvas features — including gradients, images, and basic games — so you can build even cooler visuals and interactive experiences!

Stay Updated

If you found this information useful, don’t forget to bookmark this page and Share.

HTML5 and CSS3 Compleate Series