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.
ctx.fillStyle = '#777';
ctx.fillRect(20, 20, 80, 40);
ctx.translate(140, 60);
ctx.fillStyle = '#d23';
ctx.fillRect(20, 20, 80, 40);
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);
Move the origin to the desired pivot, rotate, draw around the local origin, then restore the previous transform. See Canvas rotate().
ctx.translate(100, 50);
// ...draw transformed content...
ctx.resetTransform();
No. It changes the coordinate system for later drawing operations.
Yes. Repeated transformations are combined with the current transformation matrix.
The safest pattern is save(), translate(), draw(), restore(). resetTransform() resets all transforms to the identity matrix.
Yes. Negative x moves the origin left and negative y moves it up.
Rotation is around the current origin, so translating the origin to a pivot lets you rotate around that point.
rotate() | transform() | Canvas tutorial
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.