HTML Canvas

Master real-time graphic rendering through JavaScript-powered Canvas API operations

Canvas elements establish JavaScript-controlled rendering contexts for dynamic graphic generation. These container elements require scripting for visual outputβ€”the tag itself provides only the drawing surface framework.

What is HTML Canvas?

The <canvas> element provides a bitmap canvas on which you can draw using JavaScript. It's like a blank drawing surface where you can create:

  • Shapes (rectangles, circles, lines, paths)
  • Text with various fonts and styles
  • Images and image manipulation
  • Gradients and patterns
  • Animations and games
  • Charts and data visualizations

Key Point

Canvas delivers comprehensive programmatic graphic manipulation capabilities. JavaScript handles all rendering operations while canvas elements function purely as drawable surface containers.

The Canvas Element

To use canvas, you must define it in your HTML with width and height attributes:

Basic Canvas Element

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
  Your browser does not support the HTML canvas tag.
</canvas>

Result:

Important attributes:

  • id - Used to reference the canvas in JavaScript
  • width - Sets the canvas width in pixels (default: 300)
  • height - Sets the canvas height in pixels (default: 150)
  • The fallback text is displayed in browsers that don't support canvas

⚠️ Important

Always specify the width and height using HTML attributes, not CSS. CSS sizing can cause distortion because it scales the canvas after rendering.

Drawing a Rectangle

To draw on the canvas, you must first get the canvas context and then use drawing methods:

Example - Red Rectangle

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000;">
</canvas>

<script>
  var canvas = document.getElementById("myCanvas");
  var ctx = canvas.getContext("2d");
  ctx.fillStyle = "#FF0000";
  ctx.fillRect(0, 0, 150, 75);
</script>

Result:

Explanation:

  1. getElementById("myCanvas") - Find the canvas element
  2. getContext("2d") - Get the 2D drawing context
  3. fillStyle = "#FF0000" - Set the fill color to red
  4. fillRect(0, 0, 150, 75) - Draw a filled rectangle at (x:0, y:0) with width 150 and height 75

Canvas Coordinates

The HTML canvas is a two-dimensional grid. The upper-left corner of the canvas has coordinates (0,0).

Canvas coordinate system:
(0,0) ────────────► X-axis
β”‚
β”‚
β”‚
β–Ό
Y-axis

Key points:

  • X increases to the right
  • Y increases downward
  • All coordinates are in pixels
  • Drawing outside the canvas bounds is clipped

Drawing Shapes

Rectangle Methods

Canvas provides three methods for drawing rectangles:

Method Description
fillRect(x, y, w, h) Draws a filled rectangle
strokeRect(x, y, w, h) Draws a rectangle outline
clearRect(x, y, w, h) Clears the specified rectangular area

Example - Multiple Rectangles

<canvas id="rectCanvas" width="300" height="150" style="border:1px solid #000;">
</canvas>

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

  // Filled rectangle
  ctx.fillStyle = "#FF6347";
  ctx.fillRect(20, 20, 100, 80);

  // Stroked rectangle
  ctx.strokeStyle = "#4CAF50";
  ctx.lineWidth = 5;
  ctx.strokeRect(150, 20, 100, 80);

  // Clear rectangle (makes a hole)
  ctx.clearRect(50, 40, 40, 40);
</script>

Result:

Drawing Paths

Paths are used to draw lines, circles, arcs, and complex shapes. A path is a list of points connected by lines.

Path Methods

Method Description
beginPath() Begins a new path
moveTo(x, y) Moves the pen to a point
lineTo(x, y) Draws a line to a point
arc(x, y, r, start, end) Draws an arc or circle
closePath() Closes the current path
stroke() Draws the path outline
fill() Fills the path

Example - Drawing a Line

<canvas id="lineCanvas" width="200" height="100" style="border:1px solid #000;">
</canvas>

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

  ctx.beginPath();
  ctx.moveTo(20, 20);
  ctx.lineTo(180, 80);
  ctx.strokeStyle = "#2196F3";
  ctx.lineWidth = 5;
  ctx.stroke();
</script>

Result:

Drawing a Circle

<canvas id="circleCanvas" width="200" height="150" style="border:1px solid #000;">
</canvas>

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

  ctx.beginPath();
  ctx.arc(100, 75, 50, 0, 2 * Math.PI);
  ctx.fillStyle = "#9C27B0";
  ctx.fill();
  ctx.strokeStyle = "#000";
  ctx.lineWidth = 3;
  ctx.stroke();
</script>

Result:

arc() parameters:

  • x, y - Center coordinates
  • r - Radius
  • startAngle - Start angle in radians
  • endAngle - End angle in radians
  • 2 * Math.PI - Complete circle (360 degrees)

Drawing Text

Canvas provides methods for drawing text on the canvas:

Method Description
fillText(text, x, y) Draws filled text
strokeText(text, x, y) Draws text outline

Example - Canvas Text

<canvas id="textCanvas" width="300" height="100" style="border:1px solid #000;">
</canvas>

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

  ctx.font = "30px Arial";
  ctx.fillStyle = "#FF5722";
  ctx.fillText("Hello Canvas!", 10, 50);

  ctx.font = "20px Verdana";
  ctx.strokeStyle = "#3F51B5";
  ctx.strokeText("Outlined Text", 10, 80);
</script>

Result:

Gradients

Canvas supports linear and radial gradients that can be used to fill or stroke shapes.

Linear Gradient

<canvas id="gradientCanvas" width="200" height="100" style="border:1px solid #000;">
</canvas>

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

  // Create gradient
  var gradient = ctx.createLinearGradient(0, 0, 200, 0);
  gradient.addColorStop(0, "#FF0000");
  gradient.addColorStop(0.5, "#FFFF00");
  gradient.addColorStop(1, "#00FF00");

  // Fill with gradient
  ctx.fillStyle = gradient;
  ctx.fillRect(10, 10, 180, 80);
</script>

Result:

createLinearGradient(x0, y0, x1, y1):

  • x0, y0 - Start point coordinates
  • x1, y1 - End point coordinates
  • addColorStop(position, color) - Adds a color at a position (0 to 1)

Radial Gradient

<canvas id="radialCanvas" width="200" height="200" style="border:1px solid #000;">
</canvas>

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

  // Create radial gradient
  var gradient = ctx.createRadialGradient(100, 100, 10, 100, 100, 90);
  gradient.addColorStop(0, "#FFFFFF");
  gradient.addColorStop(1, "#FF1744");

  // Fill with gradient
  ctx.fillStyle = gradient;
  ctx.fillRect(0, 0, 200, 200);
</script>

Result:

Drawing Images

You can draw images on the canvas using the drawImage() method:

Example - Drawing an Image

<canvas id="imgCanvas" width="300" height="200" style="border:1px solid #000;">
</canvas>

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

  var img = new Image();
  img.onload = function() {
    ctx.drawImage(img, 10, 10, 280, 180);
  };
  img.src = "image.jpg";
</script>

drawImage() variations:

  • drawImage(img, x, y) - Draw at position
  • drawImage(img, x, y, width, height) - Draw and scale
  • drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh) - Crop and draw

Canvas Properties and Methods Summary

Style Properties

Property Description
fillStyle Sets fill color or gradient
strokeStyle Sets stroke color or gradient
lineWidth Sets line width
font Sets text font
textAlign Sets text alignment
globalAlpha Sets transparency (0 to 1)

Common Methods

  • fillRect(), strokeRect(), clearRect() - Rectangle methods
  • beginPath(), closePath() - Path methods
  • moveTo(), lineTo() - Drawing lines
  • arc(), arcTo() - Drawing arcs
  • quadraticCurveTo(), bezierCurveTo() - Drawing curves
  • fillText(), strokeText() - Drawing text
  • drawImage() - Drawing images
  • save(), restore() - Saving and restoring state

Test Your Knowledge