Canvas translate(): Move the Coordinate Origin

translate(x, y) moves the Canvas coordinate system by adding a translation to the current transformation matrix. After translating, coordinates are interpreted relative to the new origin.

Canvas coordinate origin before and after translate

Basic translate() example Top ↑

ctx.fillStyle = '#777';
ctx.fillRect(20, 20, 80, 40);

ctx.translate(140, 60);
ctx.fillStyle = '#d23';
ctx.fillRect(20, 20, 80, 40);
Canvas translation example.

Translations accumulate Top ↑

Calling translate() repeatedly multiplies another translation into the current transform. Use save()/restore() when the movement should apply only to one drawing.

ctx.save();
ctx.translate(120, 40);
ctx.fillRect(0, 0, 80, 40);
ctx.restore();

// Back to the previous coordinate system
ctx.fillRect(10, 10, 80, 40);

Translation is useful for rotation around a custom point Top ↑

Move the origin to the desired pivot, rotate, draw around the local origin, then restore the previous transform. See Canvas rotate().

Resetting the transform Top ↑

ctx.translate(100, 50);
// ...draw transformed content...
ctx.resetTransform();

Frequently asked questions Top ↑

Does translate() move existing Canvas pixels? Top ↑

No. It changes the coordinate system for later drawing operations.

Do translate() calls accumulate? Top ↑

Yes. Repeated transformations are combined with the current transformation matrix.

How do I undo a translation? Top ↑

The safest pattern is save(), translate(), draw(), restore(). resetTransform() resets all transforms to the identity matrix.

Can translate() use negative values? Top ↑

Yes. Negative x moves the origin left and negative y moves it up.

Why use translate() before rotate()? Top ↑

Rotation is around the current origin, so translating the origin to a pivot lets you rotate around that point.

rotate() | transform() | Canvas tutorial





plus2net.com










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer