The canvas Tag in HTML: How to Draw Graphics with Examples

html canvas tag

The HTML canvas tag draws shapes and images. It also helps you draw text with code. It gives control over 2D graphics and animations with real-time updates.

Understand the <canvas> Tag in HTML

The <canvas> tag creates a drawing space inside a web page. You use JavaScript to draw shapes or lines. Also, images or text inside it. The <canvas> tag itself is blank.

The syntax looks like this:

<canvas id="myCanvas" width="300" height="150"></canvas>
  • id lets you target the canvas with JavaScript.
  • width and height set the size of the canvas in pixels.
  • If you skip size, it defaults to 300×150 pixels.

How to Use JavaScript with the <canvas> Tag

JavaScript must select the canvas and use its getContext() method.

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
  • ctx now controls the canvas.
  • “2d” means you use the 2D drawing mode.

Draw Shapes with <canvas> Tag in HTML

Here you have to use methods on the ctx object:

Draw a Line:

ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(200, 100);
ctx.stroke();

Here is how it works:

  • beginPath() starts a new line.
  • moveTo(x, y) sets the start point.
  • lineTo(x, y) sets the end point.
  • stroke() draws the line.

Here is how to draw a rectangle:

ctx.fillStyle = "blue";
ctx.fillRect(50, 50, 100, 80);
  • fillStyle sets the color.
  • fillRect(x, y, width, height) draws a filled box.

This code shows you how to draw a Circle:

ctx.beginPath();
ctx.arc(150, 75, 50, 0, 2 * Math.PI);
ctx.fillStyle = "green";
ctx.fill();
  • arc(x, y, radius, startAngle, endAngle) defines the circle.
  • Use Math.PI to set angle values.
  • fill() paints the circle.

Here are more 2D drawing function examples:

Draw text:

ctx.font = "20px Arial";
ctx.fillStyle = "black";
ctx.fillText("Hello Canvas", 100, 50);

Clear canvas:

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

Image Manipulation with <canvas> Tag in HTML

You can draw an image and edit its pixels. This works in real-time.

const img = new Image();
img.onload = function () {
  ctx.drawImage(img, 0, 0);
  const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  const pixels = imageData.data;

  for (let i = 0; i < pixels.length; i += 4) {
    pixels[i] = 255 - pixels[i];
    pixels[i + 1] = 255 - pixels[i + 1];
    pixels[i + 2] = 255 - pixels[i + 2];
  }

  ctx.putImageData(imageData, 0, 0);
};
img.src = "photo.jpg";

This code loads an image and shows it on a canvas. It reads all the pixels (tiny dots of color) from the canvas once the image loads.

It changes each pixel’s color to its opposite by subtracting its red, green, and blue values from 255.

This creates an “inverted” or “negative” effect and puts the updated image back on the canvas so you can see the result.

Animations with the <canvas> Tag in HTML

Use requestAnimationFrame() for smooth results.

let x = 0;

function drawFrame() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  ctx.arc(x, 75, 20, 0, 2 * Math.PI);
  ctx.fillStyle = "red";
  ctx.fill();
  x += 2;
  requestAnimationFrame(drawFrame);
}

drawFrame();

This code makes a red circle move across the canvas from left to right. It starts by setting x to 0, which is the circle’s starting point.

The drawFrame function clears the canvas, draws a red circle at position x, then increases x by 2 to move the circle to the right.

The requestAnimationFrame(drawFrame) keeps calling the function again and again to create a smooth animation.

Handle Event on <canvas> Tag in HTML

Canvas does not have built-in events for clicks or keys. Use JavaScript to track events.

Mouse and Keyboard Interactions on Canvas Elements:

canvas.addEventListener("click", function (event) {
  const x = event.offsetX;
  const y = event.offsetY;
  ctx.fillStyle = "blue";
  ctx.fillRect(x - 5, y - 5, 10, 10);
});

Keyboard events work on the full page:

document.addEventListener("keydown", function (event) {
  if (event.key === "ArrowRight") {
    console.log("Move right");
  }
});

Canvas vs SVG for Graphics Rendering

Canvas draws pixels. It does not remember shapes. The SVG draws vector shapes in the DOM. Each shape stays editable.

Here are the key differences:

FeatureCanvasSVG
Shape storageNoYes
PerformanceFaster for many shapesSlower with many shapes
InteractionsManualBuilt-in
Resize supportNeeds redrawAuto-scale

Use cases:

  • Use for games or image editing with real-time updates.
  • Use SVG for charts or maps with static graphics.

Browser Support and Compatibility

The <canvas> tag works in all modern browsers.

BrowserSupport
ChromeYes
FirefoxYes
SafariYes
EdgeYes
OperaYes

Examples

Draw a Grid of Squares:

const size = 20;
for (let y = 0; y < canvas.height; y += size) {
  for (let x = 0; x < canvas.width; x += size) {
    ctx.strokeRect(x, y, size, size);
  }
}

This draws a grid over the canvas using strokeRect() in two loops.

Animate a Bouncing Ball:

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

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  ctx.arc(x, y, 10, 0, 2 * Math.PI);
  ctx.fill();
  x += dx;
  y += dy;

  if (x < 10 || x > canvas.width - 10) dx = -dx;
  if (y < 10 || y > canvas.height - 10) dy = -dy;

  requestAnimationFrame(animate);
}
animate();

This animates a ball that bounces off the canvas edge.

Draw with the Mouse:

let draw = false;

canvas.addEventListener("mousedown", () => draw = true);
canvas.addEventListener("mouseup", () => draw = false);

canvas.addEventListener("mousemove", function (event) {
  if (!draw) return;
  const x = event.offsetX;
  const y = event.offsetY;
  ctx.fillRect(x, y, 4, 4);
});

This lets you paint on the canvas using the mouse.

Wrapping Up

In this article, you learned how the <canvas> tag works, how to draw shapes or images, and how to animate with JavaScript. Also, you learned how to track mouse and keyboard events.

Here is a quick recap:

  • draws with JavaScript code
  • You can draw any shape
  • You can add image filters and real-time updates
  • You can animate frames and add interactions
  • Canvas is different from SVG in behavior and performance

FAQs

What is the use of the <canvas> tag in HTML5?

The <canvas> tag in HTML5 is used to draw graphics on a web page via JavaScript. It allows developers to render shapes, images, text, and even animations on the fly. Unlike SVG, <canvas> is bitmap-based and is ideal for game development, image editing, or dynamic visual content.

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

You can then draw on it using JavaScript:

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 100, 50);

How do you draw shapes using the <canvas> tag and JavaScript?

To draw shapes using the <canvas> element, you need to access its rendering context with JavaScript, usually using getContext("2d"). Then, use drawing methods like fillRect, strokeRect, or arc for circles.

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

// Draw rectangle
ctx.fillStyle = "blue";
ctx.fillRect(20, 20, 150, 100);

// Draw circle
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.stroke();

What is the difference between <canvas> and SVG in HTML?

Both <canvas> and SVG are used to draw graphics, but they have key differences:

  • <canvas>: Bitmap-based, ideal for dynamic graphics, games, and real-time rendering.
  • SVG: Vector-based, better for static graphics, icons, and charts where accessibility is important.

Example of <canvas>:

<canvas id="drawArea" width="200" height="100"></canvas>

How to animate using the <canvas> tag in JavaScript?

You can create animations in <canvas> using the requestAnimationFrame() method. This allows you to update your canvas graphics smoothly in a loop.

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
let x = 0;

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  ctx.arc(x, 75, 20, 0, Math.PI * 2);
  ctx.fillStyle = "green";
  ctx.fill();
  x += 2;
  requestAnimationFrame(animate);
}
animate();

Similar Reads

HTML Data Attributes with Examples

data-* attributes store extra values on elements without an extra DOM nodes or backend requests. What are data-* attributes in…

HTML meta http-equiv Attribute for Web SEO with Examples

This guide explains how to use the HTML meta http-equiv attribute, why it matters for SEO, and how browsers treat…

HTML Deprecated Tags and Modern Alternatives List

HTML tags that no longer work stay in the deprecated list. This article explains them and shows the modern replacements.…

HTML ARIA Attributes for Accessibility

The HTML ARIA attributes help users with disabilities use websites. These attributes describe roles and states for tools. Understand the…

HTML Small Tag: How to Make Text Small

The HTML small tag displays text in a smaller font size than nearby text. It shows less important or side…

Component-driven HTML Guide with Examples

This guide shows how to build HTML with separate parts as components and how each part helps in reuse and…

HTML Document Structure Guide for Beginners

A web page must follow a clear structure so browsers can read and show it correctly. This guide helps you…

HTML code Tag: How to Mark Up Code Snippets

The <code> tag in HTML shows short code, command names, or output. Use it to display text that the browser…

HTML Input Tag: How It Works, Types & Examples

The HTML input tag lets you add fields for user data in forms. You use this tag to collect text,…

How to Create HTML Nested Lists with Examples

In this article, you will learn how the browsers read nested lists in HTML and how to use them with…

Previous Article

HTML track Tag: How to Add Subtitles to Videos

Next Article

HTML embed Tag: How to Embed External Media in Web Pages

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.