Transformations
You'll learn how to move, rotate, and scale the entire canvas coordinate system to simplify complex drawings.
What Are Canvas Transformations?
Instead of manually calculating where every point should go when you want to draw something rotated or shifted, transformations let you reposition the canvas's entire grid. Think of it like moving the paper under your pen rather than changing where your pen draws.
Canvas transformations modify the coordinate system itself. When you apply translate(), rotate(), or scale(), all subsequent drawing operations use the transformed coordinates until you reset or save/restore the context state.
Core Transformation Methods
translate(x, y)
Moves the origin (0,0) to a new position. If you translate(100, 50), drawing at (0,0) now appears at (100, 50) on the actual canvas.
rotate(angle)
Rotates the coordinate system around the current origin by the specified angle in radians (not degrees). Positive values rotate clockwise.
scale(x, y)
Stretches or shrinks the coordinate system. scale(2, 1) makes everything twice as wide. Values less than 1 shrink; negative values flip.
Why Use Transformations?
Imagine drawing a clock face. Without transformations, you'd calculate the exact endpoint for each hour mark using trigonometry. With transformations, you:
- Translate to the clock's center
- Rotate to the hour angle
- Draw a simple line straight up
- Repeat for each hour
Much simpler! The canvas handles all the math for you.
Key Takeaway: Canvas transformations modify the coordinate system itself, letting you move, rotate, and scale your "drawing paper" instead of recalculating every point manually—perfect for complex patterns, rotations, and repeated elements.