Canvas API

The canvas API gives you direct control over drawing. It's perfect for creating custom graphics, games, and visualizations.

Basic Setup

Access the canvas through the trifling.canvas module:

🐢 Interactive Graphics

Drawing Shapes

Rectangles

🐢 Interactive Graphics

Lines and Paths

🐢 Interactive Graphics

Circles and Arcs

🐢 Interactive Graphics

Colors and Styles

RGB and Hex Colors

🐢 Interactive Graphics

Filled and Stroked Shapes

🐢 Interactive Graphics

Patterns and Designs

Grid Pattern

🐢 Interactive Graphics

Concentric Circles

🐢 Interactive Graphics

Checkerboard

🐢 Interactive Graphics

Animation Basics

Create simple animations by clearing and redrawing:

🐢 Interactive Graphics

Complex Shapes

Star

🐢 Interactive Graphics

Canvas Methods Reference

Drawing Rectangles

  • fillRect(x, y, width, height) - Draw filled rectangle
  • strokeRect(x, y, width, height) - Draw outlined rectangle
  • clearRect(x, y, width, height) - Clear rectangle area

Drawing Paths

  • beginPath() - Start a new path
  • closePath() - Close the current path
  • moveTo(x, y) - Move to position without drawing
  • lineTo(x, y) - Draw line to position
  • arc(x, y, radius, startAngle, endAngle) - Draw arc/circle
  • fill() - Fill the current path
  • stroke() - Stroke the current path

Styles

  • fillStyle - Color for filling (hex, rgb, rgba)
  • strokeStyle - Color for stroking
  • lineWidth - Width of lines

Try Your Own!

Create a custom design:

🐢 Interactive Graphics

Next Steps

  • Combine canvas with turtle graphics
  • Create interactive visualizations
  • Build simple games
  • Check out Trifle Imports to share canvas utilities