🎨 HTML Canvas in JavaScript – Complete Tutorial

The HTML Canvas API allows JavaScript to draw graphics directly inside a web page. It can be used to create shapes, animations, charts, games, image editing tools, and much more.

📌 What is Canvas?

The <canvas> element provides a drawable area where JavaScript can render 2D graphics (and, with other APIs such as WebGL, 3D graphics). The canvas itself is just a blank area until JavaScript draws on it.

>>"Canvas is like a blank sheet of paper where JavaScript becomes the painter."

💡 Why Use Canvas?

  • 🎮 Build browser games
  • 📊 Draw charts and graphs
  • 🎨 Create digital art and drawing apps
  • 🖼️ Edit and manipulate images
  • ✨ Build animations and visual effects

🏗 Creating a Canvas

HTML Canvas

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

🛠 Getting the Drawing Context

Before drawing, obtain the 2D rendering context.

Get Context

const canvas =
  document.getElementById("canvas");

const ctx =
  canvas.getContext("2d");

📊 Canvas Size

Canvas Dimensions

console.log(canvas.width);
console.log(canvas.height);

🎨 Drawing a Rectangle

fillRect()

ctx.fillStyle = "royalblue";

ctx.fillRect(
  50,
  50,
  150,
  100
);

⬜ Drawing an Outlined Rectangle

strokeRect()

ctx.strokeStyle = "red";

ctx.lineWidth = 4;

ctx.strokeRect(
  50,
  50,
  150,
  100
);

🧹 Clearing the Canvas

clearRect()

ctx.clearRect(
  0,
  0,
  canvas.width,
  canvas.height
);

📏 Drawing Lines

Line

ctx.beginPath();

ctx.moveTo(20, 20);

ctx.lineTo(250, 150);

ctx.stroke();

🔺 Drawing a Triangle

Triangle

ctx.beginPath();

ctx.moveTo(150, 50);

ctx.lineTo(250, 200);

ctx.lineTo(50, 200);

ctx.closePath();

ctx.stroke();

⭕ Drawing a Circle

Circle

ctx.beginPath();

ctx.arc(
  150,
  150,
  50,
  0,
  Math.PI * 2
);

ctx.fill();

🌈 Drawing an Arc

Arc

ctx.beginPath();

ctx.arc(
  150,
  150,
  80,
  0,
  Math.PI
);

ctx.stroke();

🖊 Drawing Text

Text

ctx.font =
  "30px Arial";

ctx.fillStyle =
  "green";

ctx.fillText(
  "Hello Canvas",
  50,
  100
);

🖼 Drawing Images

Draw Image

const img =
  new Image();

img.src = "photo.jpg";

img.onload = () => {

  ctx.drawImage(
    img,
    20,
    20,
    200,
    150
  );

};

🎨 Colors

Fill & Stroke Colors

ctx.fillStyle = "orange";

ctx.strokeStyle = "blue";

🖌 Line Styles

Line Width

ctx.lineWidth = 5;

ctx.lineCap = "round";

ctx.lineJoin = "round";

🌈 Gradients

Linear Gradient

const gradient =
  ctx.createLinearGradient(
    0,
    0,
    200,
    0
  );

gradient.addColorStop(
  0,
  "red"
);

gradient.addColorStop(
  1,
  "yellow"
);

ctx.fillStyle =
  gradient;

ctx.fillRect(
  20,
  20,
  200,
  100
);

🔵 Shadows

Shadow

ctx.shadowColor =
  "gray";

ctx.shadowBlur = 10;

ctx.shadowOffsetX = 5;

ctx.shadowOffsetY = 5;

💾 Saving and Restoring State

Canvas lets you save the current drawing state and restore it later.

save() & restore()

ctx.save();

ctx.fillStyle = "red";

ctx.fillRect(20,20,100,100);

ctx.restore();

🔄 Transformations

Translate

ctx.translate(
  100,
  50
);

Rotate

ctx.rotate(
  Math.PI / 4
);

Scale

ctx.scale(
  2,
  2
);

🎬 Basic Animation

Use requestAnimationFrame() to create smooth animations.

Animation

let x = 0;

function animate() {

  ctx.clearRect(
    0,
    0,
    canvas.width,
    canvas.height
  );

  ctx.fillRect(
    x,
    100,
    50,
    50
  );

  x++;

  requestAnimationFrame(
    animate
  );

}

animate();

🛠 Complete Example

HTML

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

JavaScript

const canvas =
  document.getElementById("canvas");

const ctx =
  canvas.getContext("2d");

ctx.fillStyle =
  "dodgerblue";

ctx.fillRect(
  50,
  50,
  200,
  120
);

ctx.font =
  "24px Arial";

ctx.fillStyle =
  "white";

ctx.fillText(
  "Canvas",
  100,
  120
);

📊 Common Canvas Methods

MethodPurpose
fillRect()Draws a filled rectangle.
strokeRect()Draws an outlined rectangle.
clearRect()Clears part of the canvas.
fillText()Draws filled text.
strokeText()Draws outlined text.
drawImage()Draws an image.
arc()Draws circles and arcs.
beginPath()Starts a new drawing path.
stroke()Renders the current path outline.
fill()Fills the current path.

⚠️ Limitations

  • 🖼 Canvas graphics are pixel-based and are not individual DOM elements.
  • ♿ Accessibility requires additional consideration because canvas content is not inherently semantic.
  • 🔄 Redrawing is required whenever the displayed graphics change.

Note

Use requestAnimationFrame() for smooth animations instead ofsetInterval() whenever possible. It synchronizes rendering with the browser's refresh rate.

✅ Best Practices

  • 🎨 Always call beginPath() before drawing a new shape.
  • 🧹 Clear only the portions of the canvas that need updating for better performance.
  • 💾 Use save() and restore() when changing drawing styles or transformations.
  • ⚡ Use requestAnimationFrame() for animations.
  • 📐 Set the canvas width and height attributes instead of relying only on CSS to avoid scaling issues.

🎯 Summary

The HTML Canvas API is a powerful tool for creating graphics, animations, games, and visualizations in the browser. By combining drawing methods, styling options, transformations, and animation techniques, developers can build rich and interactive graphical applications using JavaScript.