JavaScript Canvas: A Beginner’s Guide

JavaScript Canvas: A Beginner’s Guide

The HTML5 <canvas> element offers a blank canvas in the browser—literally—upon which you can draw shapes, text, images, and even animations. Instead of relying on static image files, canvas gives you fine-grained control pixel by pixel, enabling dynamic and interactive graphics. This guide will introduce you to the basics of setting up a canvas, drawing various elements, applying visual styles, animating scenes, and responding to user interactions.

In essence, Canvas provides a programmable drawing surface. JavaScript commands tell the browser what to render and when. Whether you’re sketching a simple shape or animating a bouncing ball, Canvas brings creativity and code together. Let’s dive into practical examples that you can run directly in your browser.

Setting Up the Canvas in HTML

You start by adding a <canvas> tag to your HTML and grabbing its drawing context via JavaScript. The following example shows this setup:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Canvas Setup</title>
</head>
<body>

  <canvas id="myCanvas" width="400" height="300" style="border:1px solid black;"></canvas>

  <script>

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

    ctx.fillStyle = 'lightgrey';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

  </script>

</body>
</html>

In this code, the canvas is 400×300 pixels with a black border. The script fetches the 2D drawing context and fills it with light grey, creating a neutral background to work on.

JavaScript Canvas: A Beginner’s Guide

Drawing Basic Shapes

Now that the canvas is ready, let’s draw a magic scroll using rectangles and a decorative border:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Magic Scroll</title>
</head>
<body>

  <canvas id="scrollCanvas" width="400" height="300" style="border:1px solid black;"></canvas>

  <script>
    const ctx = document.getElementById('scrollCanvas').getContext('2d');

    ctx.fillStyle = '#f1e4b3';
    ctx.fillRect(80, 60, 240, 150);

    ctx.strokeStyle = '#a27c48';
    ctx.lineWidth = 6;
    ctx.strokeRect(75, 55, 250, 160);

  </script>

</body>
</html>

Here, a warm parchment color fills the rectangle, and a thick darker outline gives it an ancient scroll-like feel.

JavaScript Canvas: A Beginner’s Guide

Drawing Paths: Wizard Hat

Paths let you draw lines and shapes by plotting points. Here’s a wizard hat using triangular paths:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Wizard Hat</title>
</head>
<body>

  <canvas id="hatCanvas" width="400" height="300" style="border:1px solid black;"></canvas>

  <script>

    const ctx = document.getElementById('hatCanvas').getContext('2d');

    ctx.beginPath();
    ctx.moveTo(200, 50);
    ctx.lineTo(140, 200);
    ctx.lineTo(260, 200);
    ctx.closePath();

    ctx.fillStyle = 'darkblue';
    ctx.fill();

    ctx.strokeStyle = 'white';
    ctx.lineWidth = 3;
    ctx.stroke();

  </script>

</body>
</html>

The triangle shape is filled in dark blue and outlined in white, giving it a defined, magical outline.

JavaScript Canvas: A Beginner’s Guide

Drawing Glowing Orb (Circle + Gradient)

Circles are drawn with arc(), and gradients add luminous effect:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Glowing Orb</title>
</head>
<body>

  <canvas id="orbCanvas" width="400" height="300" style="border:1px solid black;"></canvas>

  <script>

    const ctx = document.getElementById('orbCanvas').getContext('2d');

    const centerX = 200;
    const centerY = 150;
    const radius = 60;

    const gradient = ctx.createRadialGradient(centerX, centerY, 10, centerX, centerY, radius);
    gradient.addColorStop(0, 'rgba(255,255,150,1)');
    gradient.addColorStop(1, 'rgba(255,140,0,0)');

    ctx.beginPath();
    ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
    ctx.fillStyle = gradient;
    ctx.fill();

  </script>

</body>
</html>

A radiant glow is created with createRadialGradient, making it look like a magical light sphere.

JavaScript Canvas: A Beginner’s Guide

Colors and Gradients: Sunrise

This example combines gradients and shapes to paint a sunrise scene:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Sunrise</title>
</head>
<body>

  <canvas id="sunriseCanvas" width="400" height="300" style="border:1px solid black;"></canvas>

  <script>

    const ctx = document.getElementById('sunriseCanvas').getContext('2d');

    const grad = ctx.createLinearGradient(0, 0, 0, 300);
    grad.addColorStop(0, 'lavenderblush');
    grad.addColorStop(0.5, 'gold');
    grad.addColorStop(1, 'skyblue');
    ctx.fillStyle = grad;
    ctx.fillRect(0, 0, 400, 300);

    ctx.beginPath();
    ctx.arc(200, 240, 50, 0, Math.PI);
    ctx.fillStyle = 'orange';
    ctx.fill();

  </script>

</body>
</html>

A gradient sky fills the canvas and a half-circle sun appears on the horizon in warm orange.

JavaScript Canvas: A Beginner’s Guide

Drawing Styled Text

Let’s add a greeting in a bold, centered style:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Canvas Greeting</title>
</head>
<body>

  <canvas id="textCanvas" width="400" height="150" style="border:1px solid black;"></canvas>

  <script>

    const ctx = document.getElementById('textCanvas').getContext('2d');

    ctx.font = 'bold 24px Serif';
    ctx.fillStyle = 'darkgreen';
    ctx.textAlign = 'center';
    ctx.fillText('Welcome to Lusaka Canvas!', 200, 80);

  </script>

</body>
</html>

The text is centered and styled, creating an appealing welcome message.

JavaScript Canvas: A Beginner’s Guide

Drawing an Image

Here’s how to render an image (e.g. a dragon):

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Canvas Image</title>
</head>
<body>

  <canvas id="dragonCanvas" width="400" height="300" style="border:1px solid black;"></canvas>

  <script>

    const ctx = document.getElementById('dragonCanvas').getContext('2d');
    const img = new Image();
    img.src = 'https://cataas.com/cat?width=120&height=120';
    img.onload = () => {
      ctx.drawImage(img, 140, 90, 120, 120);
    };

  </script>

</body>
</html>

The image loads and displays on the canvas when ready.

JavaScript Canvas: A Beginner’s Guide

Transformations: Rotating Rune

We rotate and animate a rune-like cross on the canvas:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Rotating Rune</title>
</head>
<body>

  <canvas id="runeCanvas" width="400" height="300" style="border:1px solid black;"></canvas>

  <script>

    const ctx = document.getElementById('runeCanvas').getContext('2d');
    let angle = 0;

    function draw() {

      ctx.clearRect(0, 0, 400, 300);
      ctx.save();
      ctx.translate(200, 150);
      ctx.rotate(angle);

      ctx.beginPath();
      ctx.moveTo(-50, 0);
      ctx.lineTo(50, 0);
      ctx.moveTo(0, -50);
      ctx.lineTo(0, 50);
      ctx.strokeStyle = 'teal';
      ctx.lineWidth = 5;
      ctx.stroke();

      ctx.restore();
      angle += 0.02;
      requestAnimationFrame(draw);

    }

    draw();

  </script>

</body>
</html>

The rune rotates smoothly, thanks to save(), translate(), and rotate() around its center.

JavaScript Canvas: A Beginner’s Guide

Simple Animation: Milo the Cat

We animate a cat bouncing around the canvas:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Bouncing Milo</title>
</head>
<body>

  <canvas id="catCanvas" width="500" height="300" style="border:1px solid black;"></canvas>

  <script>

    const ctx = document.getElementById('catCanvas').getContext('2d');
    const img = new Image();
    img.src = 'https://cataas.com/cat?width=80&height=80';
    let x = 50, y = 50, dx = 4, dy = 3;

    img.onload = () => {

      function animate() {

        ctx.clearRect(0, 0, 500, 300);
        ctx.drawImage(img, x, y, 80, 80);

        if (x + 80 > 500 || x < 0) dx = -dx;
        if (y + 80 > 300 || y < 0) dy = -dy;
        x += dx; y += dy;

        requestAnimationFrame(animate);

      }

      animate();

    };

  </script>

</body>
</html>

Milo bounces around inside the canvas borders with lifelike motion.

JavaScript Canvas: A Beginner’s Guide

Interactivity: Click to Draw Stars

Let’s draw glowing stars wherever the user clicks:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Interactive Stars</title>
</head>
<body>

  <canvas id="starCanvas" width="500" height="300" style="border:1px solid black;"></canvas>

  <script>

    const canvas = document.getElementById('starCanvas');
    const ctx = canvas.getContext('2d');

    canvas.addEventListener('click', (e) => {

      const rect = canvas.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;

      const grad = ctx.createRadialGradient(x, y, 5, x, y, 20);
      grad.addColorStop(0, 'yellow');
      grad.addColorStop(1, 'rgba(255,165,0,0)');

      ctx.beginPath();
      ctx.arc(x, y, 20, 0, Math.PI * 2);
      ctx.fillStyle = grad;
      ctx.fill();

    });

  </script>

</body>
</html>

Each click produces a glowing radial star where you clicked. A magical effect!

JavaScript Canvas: A Beginner’s Guide

Conclusion

You’ve learned how to set up the canvas, draw shapes, gradients, text, and images, apply rotations and animations, and engage with mouse interactivity. The possibilities are endless—mix these techniques to build games, visualizations, or expressive art tools. Experiment, explore, and have fun creating with Canvas!

References

If you want to learn more, these resources are excellent starting points:

Scroll to Top