Skip to content
Tutorials Center
My learning

Topics

Lesson 84 of 122 ยท Graphics

Drawing and Animating with Canvas

Go beyond rectangles on the HTML canvas. Draw paths and arcs, write text, place images with drawImage, paint gradients and animate with requestAnimationFrame.

In Canvas Basics you set up a canvas, got its 2D context and painted rectangles. Rectangles are a fine start, but most drawings need lines, curves, circles, words and pictures. And the real power of canvas shows when things start to move.

This lesson covers the rest of the everyday 2D toolkit: paths and arcs, text, images, gradients and smooth animation with requestAnimationFrame. By the end you'll be able to build simple charts, illustrations and games.

Paths

Every shape other than a rectangle is drawn as a path. Working with paths is a three-step routine:

  1. Call ctx.beginPath() to start a fresh path.
  2. Describe the outline with methods like moveTo() and lineTo(). Nothing is drawn yet.
  3. Call ctx.fill() and/or ctx.stroke() to paint it with the current styles.

The outline methods work like the SVG path commands from SVG Paths, Text and Gradients:

Method What it adds to the path
moveTo(x, y) Lifts the pen and moves it to a point
lineTo(x, y) A straight line to a point
closePath() A line back to the start of the current sub-path
arc(x, y, radius, startAngle, endAngle, counterclockwise) A circular arc around a center
quadraticCurveTo(cpx, cpy, x, y) A curve with one control point
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) A curve with two control points
rect(x, y, w, h) / roundRect(x, y, w, h, radii) A rectangle, optionally with rounded corners

Angles in canvas are measured in radians, not degrees. A full circle is 2 * Math.PI (about 6.28), half a circle is Math.PI. Angle 0 points to the right (3 o'clock), and positive angles go clockwise, because the y-axis points down.

Paths and arcs

Notice how often beginPath() appears. If you forget it, the new outline is added to the old path, and the next fill() or stroke() repaints everything from before as well. Forgetting beginPath() is the classic canvas bug: shapes mysteriously change color or get connected by stray lines.

Two more style properties shape strokes: lineCap ("butt", "round" or "square") for line ends, and lineJoin ("miter", "round" or "bevel") for corners. ctx.setLineDash([8, 4]) makes dashed lines.

Text

Canvas can draw text, too:

  • ctx.font takes a CSS font shorthand, such as "bold 24px system-ui, sans-serif". Size and family are required.
  • ctx.fillText(text, x, y) paints filled text; ctx.strokeText(text, x, y) paints outlined text. An optional fourth argument sets a maximum width, and the text is squeezed to fit.
  • ctx.textAlign sets how text lines up with x: "start" (default), "end", "left", "right" or "center".
  • ctx.textBaseline sets what y refers to: "alphabetic" (default, the baseline), "top", "middle", "bottom" and a few others.
  • ctx.measureText(text).width tells you how wide a string will be, which is useful for centering things or drawing a box behind a label.

Canvas text doesn't wrap. If you need several lines, measure the words and call fillText once per line. And remember from the previous lesson: canvas text is just pixels, so important information must also exist as real text on the page.

Images

ctx.drawImage() copies an image onto the canvas. The image can be an <img> element, another canvas, a video frame or an image bitmap. It comes in three forms:

JavaScript
ctx.drawImage(image, x, y);                       // natural size
ctx.drawImage(image, x, y, width, height);        // scaled
ctx.drawImage(image, sx, sy, sw, sh,              // crop a source rectangleโ€ฆ
                     dx, dy, dw, dh);             // โ€ฆand draw it here

The image must be loaded before you draw it; drawing an image that hasn't finished loading draws nothing. Create the image, wait for it, then draw. The decode() method returns a promise that resolves when the image is ready:

Drawing, scaling and cropping an image

Images can be any format the browser supports, including SVG, which is rasterized at the size you draw it.

Tainted canvases. If you draw an image from another origin that doesn't allow cross-origin use (through CORS), the canvas becomes tainted. You can still see the drawing, but reading the pixels back with getImageData() or exporting them with toDataURL() throws a security error. That protects private images from being copied by other sites. The TryIt preview runs in an isolated sandbox, so drawn images taint the canvas there; reading pixels is something to try in your own projects.

Gradients

fillStyle and strokeStyle can be gradients instead of colors. You create a gradient object, add color stops, and assign it:

  • ctx.createLinearGradient(x0, y0, x1, y1) blends along the line from (x0, y0) to (x1, y1).
  • ctx.createRadialGradient(x0, y0, r0, x1, y1, r1) blends between two circles: a start circle and an end circle.
  • gradient.addColorStop(offset, color) sets a color at a position from 0 to 1.

Unlike SVG gradients, canvas gradients use canvas coordinates, not coordinates relative to each shape. A gradient from x = 0 to x = 400 looks the same no matter which shape you fill with it; each shape just shows its own slice.

Linear and radial gradients

The moon's last color stop is fully transparent, so it fades into a soft glow. Filling a square with that gradient is enough to make something that looks round.

Animation with requestAnimationFrame

Animation on a canvas is a loop: clear the canvas, draw the next frame, repeat. The right tool for the loop is requestAnimationFrame(callback). It asks the browser to call your function just before the next screen repaint, usually 60 times per second (more on fast displays). It also pauses automatically in background tabs, which saves battery.

The callback receives a timestamp in milliseconds. Use it to move things by elapsed time, not by a fixed step per frame. Otherwise the animation runs twice as fast on a 120 Hz screen as on a 60 Hz one.

A bouncing ball

The pieces of a solid animation loop are all here:

  • Update the state (position) using dt, the time since the previous frame.
  • Clear the canvas, then draw the new frame from the state.
  • Schedule the next frame by calling requestAnimationFrame again.
  • Stop with cancelAnimationFrame(id) using the ID the last request returned.

Avoid setInterval for animation. It isn't synchronized with the screen's refresh, so motion can stutter, and it keeps running in hidden tabs.

Respect reduced motion. Some people get dizzy or distracted from movement on screen and ask their system to reduce it. Check window.matchMedia("(prefers-reduced-motion: reduce)").matches and start decorative animations paused, or skip them, when it's true. Always give users a way to pause motion that lasts more than a few seconds, like the button above.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. You draw a red circle, then a blue square with rect() and fill(), and the circle turns blue too. What did you forget?

    Without beginPath(), the square is added to the circle's path, so fill() repaints both with the new color.
  2. 2. Which call draws a full circle centered at (100, 100) with radius 50?

    Angles are in radians, so a full turn is 2 * Math.PI. There is no circle() method, and Math.PI alone draws only half a circle.
  3. 3. Why might drawImage() draw nothing even though the image URL is correct?

    Wait for the image with decode() or a load event before drawing it.
  4. 4. Why should an animation move objects based on elapsed time instead of a fixed amount per frame?

    Frame rates differ between devices. Multiplying speed by elapsed time keeps the motion consistent.

Summary

  • Draw shapes as paths: beginPath(), outline methods like moveTo, lineTo and arc, then fill() or stroke().
  • Angles are in radians; a full circle is 2 * Math.PI, and positive angles turn clockwise.
  • font, fillText, textAlign, textBaseline and measureText handle text, which never wraps on its own.
  • drawImage() draws, scales and crops images once they've loaded; cross-origin images can taint the canvas.
  • createLinearGradient and createRadialGradient make gradients in canvas coordinates.
  • Animate with requestAnimationFrame, using elapsed time, clearing and redrawing each frame, and offer a way to pause.

Next lesson: Math with MathML.