Skip to content

Canvas Text and Images

This lesson explains Canvas Text and Images with clear examples, use cases, and best practices so you can use HTML5 APIs confidently in real web applications.

HTML5 Canvas Text & Images Overview

HTML5 Canvas can draw text and images directly on a pixel-based drawing surface using JavaScript. This makes Canvas useful for banners, charts, games, image editors, dashboards, thumbnails, watermarks, visual effects, and custom graphics that need dynamic rendering.

The Canvas 2D context provides text methods such as fillText(), strokeText(), and measureText(), along with image methods such as drawImage(). Developers can control font styles, alignment, colors, shadows, image scaling, cropping, and positioning.

Feature Description
Canvas Text Draws filled or outlined text on the canvas.
Canvas Images Draws images, videos, or other canvases.
Font Styling Controls font size, family, weight, and style.
Text Alignment Aligns text horizontally and vertically.
Image Scaling Resizes images while drawing them.
Image Cropping Draws selected portions of an image.

Canvas Text and Image Example

<canvas
  id="mediaCanvas"
  width="600"
  height="350">
  Your browser does not support canvas.
</canvas>

<script>
  const canvas = document.querySelector("#mediaCanvas");
  const ctx = canvas.getContext("2d");

  ctx.font = "bold 32px Arial";
  ctx.fillStyle = "blue";
  ctx.fillText("HTML5 Canvas", 40, 60);

  const image = new Image();

  image.addEventListener("load", () => {
    ctx.drawImage(image, 40, 100, 240, 160);
  });

  image.src = "/images/sample.jpg";
</script>

This example draws styled text on the canvas and loads an image before drawing it. Images must be loaded before calling drawImage() to avoid rendering errors.

Canvas Text Methods

Canvas text is drawn as pixels, not selectable HTML text. Use it for graphics, labels, charts, games, and visual effects rather than important page content.

Method Purpose Example Syntax
fillText() Draws filled text. ctx.fillText("Hello", x, y)
strokeText() Draws outlined text. ctx.strokeText("Hello", x, y)
measureText() Measures text width and metrics. ctx.measureText("Hello")
font Sets font style, size, and family. ctx.font = "24px Arial"
textAlign Sets horizontal alignment. ctx.textAlign = "center"
textBaseline Sets vertical alignment baseline. ctx.textBaseline = "middle"

Canvas Image Methods

The drawImage() method can draw an image at its original size, scale it to a new size, or crop a specific region before drawing.

Syntax Purpose
ctx.drawImage(image, x, y) Draws the image at its original size.
ctx.drawImage(image, x, y, width, height) Draws and scales the image to a custom size.
ctx.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh) Crops part of an image and draws it to the canvas.
new Image() Creates an image object that can be loaded and drawn.
image.onload Runs code after the image is loaded.

Draw Styled Text Example

// Draw styled text on Canvas

const canvas = document.querySelector("#mediaCanvas");
const ctx = canvas.getContext("2d");

ctx.font = "bold 36px Arial";
ctx.fillStyle = "#1d4ed8";
ctx.textAlign = "center";
ctx.textBaseline = "middle";

ctx.fillText(
  "Canvas Text",
  canvas.width / 2,
  80
);

ctx.strokeStyle = "#111827";
ctx.lineWidth = 2;
ctx.strokeText(
  "Canvas Text",
  canvas.width / 2,
  80
);

This example draws centered filled text and adds an outline using strokeText(). Canvas text can be styled with fonts, colors, shadows, alignment, and transparency.

Draw and Scale Image Example

// Draw and scale an image on Canvas

const canvas = document.querySelector("#mediaCanvas");
const ctx = canvas.getContext("2d");

const image = new Image();

image.addEventListener("load", () => {
  ctx.drawImage(
    image,
    50,
    120,
    300,
    180
  );
});

image.src = "/images/photo.jpg";

The image is drawn only after the load event fires. This ensures the browser has fully loaded the image before Canvas tries to render it.

Crop Image with Canvas Example

// Crop part of an image

const canvas = document.querySelector("#mediaCanvas");
const ctx = canvas.getContext("2d");

const image = new Image();

image.addEventListener("load", () => {
  ctx.drawImage(
    image,
    100,
    80,
    250,
    200,
    40,
    40,
    300,
    220
  );
});

image.src = "/images/photo.jpg";

The first four numbers after the image define the source crop area. The last four numbers define where and how large the cropped image should be drawn on the canvas.

Canvas Text and Image Use Cases

Use Case How Canvas Helps
Image Editors Add text, crop images, resize images, and apply filters.
Charts and Dashboards Draw labels, legends, icons, and visual data.
Games Render sprites, score text, backgrounds, and animations.
Watermarks Add text or logo overlays to images.
Thumbnails Generate image previews and resized versions.
Certificates and Posters Generate custom graphics with user-provided text and images.

Canvas Text and Image Best Practices

  • Load images before calling drawImage().
  • Use semantic HTML for important text that users need to read or select.
  • Provide accessible alternatives when canvas content communicates meaning.
  • Use measureText() to calculate text width before layout.
  • Scale canvas correctly for high-DPI and retina displays.
  • Optimize large images before drawing them repeatedly.
  • Avoid drawing cross-origin images without proper CORS headers.
  • Clear the canvas before redrawing dynamic text or images.

Common Canvas Text and Image Mistakes

  • Calling drawImage() before the image has loaded.
  • Using Canvas text for important page content without HTML alternatives.
  • Forgetting that Canvas text is not selectable or searchable.
  • Not handling broken image loading errors.
  • Drawing very large images repeatedly without optimization.
  • Ignoring cross-origin restrictions when exporting canvas content.
  • Not scaling canvas for high-DPI screens.
  • Assuming screen readers can automatically read canvas pixels.

Key Takeaways

  • Canvas can draw styled text using fillText() and strokeText().
  • Canvas can draw, resize, crop, and combine images using drawImage().
  • Images must load before being drawn on the canvas.
  • Canvas text is pixel-based and not automatically accessible.
  • Use Canvas for graphics, games, image editing, dashboards, and visual effects.
  • Provide accessible alternatives when canvas content contains meaningful information.

Pro Tip

Use Canvas text for visual graphics, not primary page content. If the text needs to be searchable, selectable, translated, or read by screen readers, use real HTML text and use Canvas only for the visual enhancement.