Skip to content
Tutorials Center
My learning

Topics

Lesson 105 of 156 ยท Browser APIs

Canvas Drawing from JavaScript

Draw shapes, paths, text and images on a canvas with the 2D context, then animate them smoothly with requestAnimationFrame and a delta-time game loop.

The <canvas> element is a blank rectangle of pixels that you paint with JavaScript. Unlike SVG or normal HTML, nothing you draw becomes an element you can click or style; it's just colored pixels, like a painter's canvas. That makes it very fast for things that change constantly: games, charts with thousands of points, image filters, particle effects, signature pads and visualizations.

In this lesson you'll learn how to get the 2D drawing context, draw rectangles, paths, text and images, handle crisp rendering on high-density screens, and build an animation loop with requestAnimationFrame(). If you only need to show a few static graphics, plain HTML or inline SVG is usually simpler; reach for canvas when you need to redraw a lot, often.

Getting a context

A canvas has a size in pixels set by its width and height attributes (the default is 300 by 150). You draw through a context object obtained with getContext("2d").

HTML
<canvas id="board" width="300" height="150"></canvas>

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

Coordinates start at the top-left corner: x grows to the right and y grows downward. The point (0, 0) is the top-left pixel.

Set the size with the width and height attributes (or properties), not with CSS alone. CSS only stretches the finished bitmap, which makes everything blurry. Changing canvas.width also clears the canvas.

Rectangles, colors and text

Rectangles are the one shape with dedicated methods. Colors come from two state properties: fillStyle (the inside) and strokeStyle (the outline). Both accept any CSS color string.

Method What it does
fillRect(x, y, w, h) Filled rectangle
strokeRect(x, y, w, h) Outlined rectangle
clearRect(x, y, w, h) Erase to transparent
fillText(text, x, y) Draw text with the current font and fillStyle
strokeText(text, x, y) Draw outlined text

The context is a state machine: fillStyle, lineWidth, font and others stay set until you change them. ctx.save() pushes the current state onto a stack and ctx.restore() pops it back, which keeps one drawing function from leaking settings into the next.

Paths

Everything else is drawn as a path: a list of points and curves that you describe first and paint afterward.

  1. ctx.beginPath() starts a new path.
  2. Describe it with moveTo, lineTo, arc, rect, quadraticCurveTo, bezierCurveTo and so on.
  3. Paint it with ctx.fill() and/or ctx.stroke().
flowchart LR
  A["beginPath()"] --> B["moveTo / lineTo / arc ..."]
  B --> C{"Paint it"}
  C --> D["fill()"]
  C --> E["stroke()"]
  D --> F["Next shape: beginPath() again"]
  E --> F

Describe a path first; nothing appears until you call fill() or stroke(). Start the next shape with beginPath().

Forgetting beginPath() is the classic bug: the old path is still there, so every stroke() redraws all earlier shapes in the new color. arc(x, y, radius, startAngle, endAngle) takes angles in radians, so a full circle runs from 0 to Math.PI * 2.

Shapes, paths and text

Transforms

Instead of calculating rotated coordinates yourself, you can move the coordinate system. translate(dx, dy) moves the origin, rotate(radians) turns the axes around it, and scale(sx, sy) stretches them. The standard pattern is save(), transform, draw at simple coordinates, restore(). Transforms apply to everything drawn afterward, so wrapping them in save() and restore() is essential.

JavaScript
// Read-only: draw a square rotated 30 degrees around its center
ctx.save();
ctx.translate(150, 100);            // move the origin to the square's center
ctx.rotate((30 * Math.PI) / 180);   // degrees to radians
ctx.fillRect(-25, -25, 50, 50);     // so the square is centered on the origin
ctx.restore();                      // back to the normal coordinate system

Images

ctx.drawImage(image, x, y) draws an <img>, another canvas, a <video> frame or an ImageBitmap. The image must be loaded first, so wait for its load event. Drawing images from another origin "taints" the canvas: it still displays, but getImageData() and toDataURL() then throw a security error unless the server sent CORS headers and you set img.crossOrigin = "anonymous".

JavaScript
// Read-only: load first, then draw
const sunset = new Image();
sunset.addEventListener("load", () => {
  ctx.drawImage(sunset, 0, 0, 200, 120); // x, y, width, height (scaled)
});
sunset.src = "/samples/sunset.svg";

Once you have drawn something, canvas.toBlob(callback, "image/png") turns it into a file you can download or upload (see Files and Blobs), and ctx.getImageData() gives you raw pixel values for filters.

Crisp drawing on high-density screens

On a phone or a laptop with a "Retina" display, one CSS pixel is two or three device pixels. A canvas drawn at its CSS size looks soft. The fix is to make the bitmap bigger and scale the context to match:

JavaScript
// Read-only: a reusable crisp-canvas helper
function setupCanvas(canvas, cssWidth, cssHeight) {
  const ratio = window.devicePixelRatio || 1;
  canvas.width = Math.round(cssWidth * ratio);   // real pixels
  canvas.height = Math.round(cssHeight * ratio);
  canvas.style.width = cssWidth + "px";          // layout size
  canvas.style.height = cssHeight + "px";
  const ctx = canvas.getContext("2d");
  ctx.scale(ratio, ratio);                       // keep drawing in CSS pixels
  return ctx;
}

After this, you still draw with the coordinates you expect, but lines and text come out sharp.

Animation with requestAnimationFrame

To animate, you erase the canvas and redraw it many times per second. Do not use setInterval for this. requestAnimationFrame(callback) asks the browser to call your function right before the next screen repaint, usually 60 times a second (or 120 or more on fast displays). It pauses automatically in background tabs, saving battery, and it stays in step with the display, so motion is smooth.

The loop calls itself again at the end of every frame. The callback receives a timestamp in milliseconds, which you use to calculate how much time has passed.

flowchart TD
  A["requestAnimationFrame(frame)"] --> B["frame(timestamp)"]
  B --> C["dt = time since last frame"]
  C --> D["Update: x += speed * dt"]
  D --> E["Draw: clearRect, then draw shapes"]
  E --> F["requestAnimationFrame(frame)"]
  F --> B

Every frame: measure time, update positions, clear and redraw, then ask for the next frame.

Delta time

If you move an object 5 pixels per frame, it moves twice as fast on a 120 Hz screen as on a 60 Hz screen. Instead, store the speed in pixels per second and multiply by the elapsed time dt (in seconds) each frame. The object then moves at the same speed on every device, even when frames are dropped.

A bouncing ball with delta time

Three details in that code are worth copying into your own loops:

  • requestAnimationFrame returns an id that you pass to cancelAnimationFrame() to stop the loop.
  • Reset the clock on resume. Otherwise the first frame after a pause sees a huge dt, and the ball jumps.
  • Separate update from draw. Update changes numbers, draw only paints them. This makes the logic easy to test and lets you change frame rates later.

Interacting with a canvas

Because a canvas has no objects, you handle events on the canvas element and work out what you hit yourself. event.offsetX and event.offsetY give the pointer position in the canvas's own coordinates (as long as the CSS size equals the bitmap size). Then you compare it to your shapes, for example with a distance check for circles. Keep the shapes in an array of plain objects and redraw from that data, rather than reading things back from the pixels.

Draw with the pointer

Pointer events work for mouse, touch and pen alike, and touch-action: none stops the browser from scrolling the page while the user draws. The drawing is stored as data and redrawn each time, so "undo" would be as simple as removing the last stroke.

Performance tips

  • Clear only when needed. If nothing changed, skip the frame. Many apps redraw on demand instead of continuously.
  • Batch paths. Many shapes with the same style can share one path and a single fill().
  • Avoid fractional coordinates for sharp lines (a 1-pixel line at x = 10 is blurry, at x = 10.5 it is crisp).
  • Layer canvases. Put a static background on one canvas and moving objects on another stacked on top of it.
  • Use OffscreenCanvas in a worker for heavy rendering that should not block the page, and WebGL or WebGPU for 3D and very large scenes.
  • Provide a text alternative. Content inside a canvas is invisible to screen readers, so add fallback text between the tags and an aria-label that describes what the canvas shows.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is it a mistake to size a canvas only with CSS (for example width 600px in a stylesheet)?

    The width and height attributes set the size of the pixel grid. CSS scales that grid, it does not add pixels.
  2. 2. A circle is drawn with ctx.arc(x, y, 20, 0, Math.PI * 2). What does the last argument mean?

    Canvas angles are in radians, and a full turn is 2 times pi.
  3. 3. What happens if you forget beginPath() before drawing a second shape and calling stroke()?

    A path keeps collecting segments until beginPath() is called, so each stroke() repaints all of them.
  4. 4. Why multiply speed by delta time in an animation loop?

    Speed in pixels per second times elapsed seconds gives the distance for this frame, so movement does not depend on the frame rate.
  5. 5. Which is the right way to stop an animation loop started with requestAnimationFrame?

    requestAnimationFrame returns an id, and cancelAnimationFrame(id) cancels the pending callback. Do not request another frame and the loop ends.

Summary

  • A <canvas> is a bitmap. Set its width and height attributes, then draw through getContext("2d"). The origin is the top-left corner and y grows downward.
  • Use fillRect, strokeRect, fillText for simple things, and paths (beginPath, moveTo, lineTo, arc, then fill or stroke) for everything else. Angles are in radians.
  • The context keeps state; wrap temporary changes and transforms in save() and restore().
  • Scale the bitmap by devicePixelRatio for sharp output on high-density screens.
  • Animate with requestAnimationFrame(), store speeds per second, multiply by delta time, separate update from draw, and stop with cancelAnimationFrame().
  • Canvas content is invisible to assistive technology, so add a text alternative.

Next: Streams API in the Browser - process data piece by piece as it arrives.