HTML Canvas


The HTML <canvas> element gives you a drawing area inside a web page. Instead of inserting an image file, you create graphics using JavaScript. You can draw shapes, lines, text, charts and even build animations or small games. Canvas is one of the most powerful features in HTML because it lets you turn simple code into custom visuals that update in real time. In this chapter, you will learn how canvas works, how to set it up and how to draw different basic elements.

What Is the Canvas Element

<canvas> is a rectangular space on your page. On its own, the canvas stays blank because HTML cannot draw anything directly. All drawings happen through JavaScript. You first select the canvas using JavaScript, then you use the canvas API to draw shapes. Think of canvas as a blank painting board and JavaScript as the brush.

Basic Syntax

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

The width and height define the drawing area. If you skip them, the default size becomes 300×150 pixels. It is always better to set width and height using attributes instead of CSS to avoid blurring.

Setting Up the Canvas Context

Canvas works with “contexts.” The most common one is the 2D context, used for shapes, text and simple objects. You must access this context before drawing anything.

Example

<canvas id="box" width="400" height="200"></canvas>

<script>
  const canvas = document.getElementById("box");
  const ctx = canvas.getContext("2d");
</script>

Here, ctx becomes your main drawing tool. Every shape, line or text will be created through this context.

Drawing Rectangles on Canvas

Rectangles are the simplest shapes on canvas. You can draw filled rectangles, outlined rectangles or clear areas inside them.

Main Functions

  • fillRect(x, y, width, height)

  • strokeRect(x, y, width, height)

  • clearRect(x, y, width, height)

Example

<canvas id="demo" width="400" height="200"></canvas>

<script>
  const c = document.getElementById("demo");
  const ctx = c.getContext("2d");

  ctx.fillStyle = "lightblue";
  ctx.fillRect(20, 20, 120, 80);

  ctx.strokeStyle = "black";
  ctx.strokeRect(160, 20, 120, 80);

  ctx.clearRect(40, 40, 30, 30);
</script>

This example shows a filled rectangle, an outlined rectangle and a cleared space inside the first one.

Drawing Lines and Paths

Lines are created using paths. You move the pen using moveTo() and draw with lineTo().

Example

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

beginPath() tells canvas to start a new drawing. You can create shapes by joining multiple lines.

Drawing Circles and Arcs

You can draw arcs or full circles using the arc() method.

Syntax

arc(x, y, radius, startAngle, endAngle)

Angles are measured in radians.

Example

ctx.beginPath();
ctx.arc(100, 100, 40, 0, Math.PI * 2);
ctx.fillStyle = "orange";
ctx.fill();

This creates a filled circle.

Drawing Text on Canvas

Canvas supports two types of text:

  • fillText(text, x, y)

  • strokeText(text, x, y)

You can style the text with:

  • ctx.font = "20px Arial"

  • ctx.fillStyle

  • ctx.strokeStyle

Example

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

Changing Colors and Styles

Canvas uses JavaScript properties to change colors, line thickness and styles.

Common Settings

  • fillStyle

  • strokeStyle

  • lineWidth

  • lineCap

  • globalAlpha (for transparency)

Example

ctx.lineWidth = 4;
ctx.strokeStyle = "red";
ctx.globalAlpha = 0.6;
ctx.strokeRect(50, 50, 100, 50);

Working With Gradients

Canvas supports two types of gradients:

  • linear gradients

  • radial gradients

Linear Gradient Example

const g = ctx.createLinearGradient(0, 0, 200, 0);
g.addColorStop(0, "blue");
g.addColorStop(1, "white");

ctx.fillStyle = g;
ctx.fillRect(20, 20, 200, 80);

Gradients help you create smoother backgrounds or modern graphics.

Drawing Images on Canvas

You can load an image and draw it inside the canvas using the drawImage() method.

Example

const img = new Image();
img.src = "car.png";

img.onload = function() {
  ctx.drawImage(img, 20, 20, 150, 80);
}

This allows you to resize, crop or animate images.

Canvas and Animation

Canvas animation works by redrawing the canvas many times per second. You clear the canvas, update positions and redraw objects. This is commonly used for games or animated charts.

Example Structure

function animate() {
  ctx.clearRect(0, 0, 400, 200);
  // draw moving objects here
  requestAnimationFrame(animate);
}

animate();

requestAnimationFrame() provides a smooth animation loop.

Canvas vs SVG

Canvas is pixel-based. SVG is shape-based. Canvas redraws everything on each update, while SVG keeps elements as separate objects. Canvas is better for fast animations or games, while SVG is better for icons, diagrams and scalable shapes.

Complete Example Drawing Multiple Elements

<canvas id="final" width="500" height="250"></canvas>

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

  // rectangle
  ctx.fillStyle = "lightgreen";
  ctx.fillRect(20, 20, 120, 70);

  // circle
  ctx.beginPath();
  ctx.arc(220, 60, 40, 0, Math.PI * 2);
  ctx.fillStyle = "skyblue";
  ctx.fill();

  // text
  ctx.font = "20px Arial";
  ctx.fillStyle = "black";
  ctx.fillText("Canvas Demo", 20, 130);
</script>

This example combines shapes, text and colors to show how flexible canvas can be.

Summary of HTML Canvas

Canvas provides a drawing surface inside your web page that can create shapes, lines, text, images and animations using JavaScript. You learned how to set up a canvas, create rectangles, circles, paths, text, gradients and images. You also saw how animations work and how canvas compares with SVG. With practice, canvas becomes useful for charts, custom graphics, dashboards and interactive apps.


Practice Questions

Q1. Create a <canvas> element of size 400x200 with a border.

Q2. Draw a horizontal line from (10,10) to (200,10).

Q3. Fill a blue rectangle from (30,30) with width=100, height=50.

Q4. Draw a circle with radius 40 at the center (100,100).

Q5. Display the text "Canvas Rocks!" on canvas at position (50,80).

Q6. Use JavaScript to change the fill color to green.

Q7. Load and draw an image onto the canvas.

Q8. Create a triangle using lineTo() method.

Q9. Draw two overlapping rectangles with different colors.

Q10. Use canvas to simulate a basic graph bar or grid.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top