Canvas Translate

What You’ll Learn
ctx.translate(x, y) shifts the origin (0,0) of the canvas coordinate system. After translating, drawing at (0,0) happens at the new location.
This is one of the most useful transforms because it makes rotation and scaling around a point much easier.
⚡ Quick Reference
ctx.translate(x, y);+ right / - leftMove origin horizontally
+ down / - upMove origin vertically
save() / restore()Avoid cumulative shifts
translate → rotateCommon for “rotate around point”
👀 Live Preview — Moving the Origin
Adjust translateX/Y and see how the same drawing commands render at different positions. The left panel uses no translation; the right panel uses translation and draws relative to (0,0).
Tip: Translation is usually the first step before rotation: translate to the pivot point, rotate, then draw centered around the origin.
Translate Then Draw (Legacy-Style Example)
Draw a rectangle, translate the context, then draw the same rectangle again. The second rectangle appears shifted.
<canvas id="myCanvas" width="400" height="260"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// Original
ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 100, 100);
// Shift the origin
ctx.translate(150, 150);
// Same draw call, different result
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 100);
</script>Translate One Shape Only (save/restore)
Scope the translation so it does not affect later drawings.
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Normal
ctx.fillStyle = '#0f172a';
ctx.fillRect(30, 40, 90, 70);
// Translated only for this draw
ctx.save();
ctx.translate(160, 70);
ctx.fillStyle = '#2563eb';
ctx.fillRect(0, 0, 90, 70);
ctx.restore();
// Back to normal coordinates
ctx.fillStyle = '#16a34a';
ctx.fillRect(30, 140, 90, 70);💡 Best Practices
Do
- Translate to your object’s anchor point before rotating/scaling
- Use
save()/restore()for per-object transforms - Reset transforms each animation frame if you do global transforms
- Think in local coordinates: draw shapes around (0,0) after translating
- Keep transform order intentional (translate then rotate is common)
Don’t
- Forget that translate() persists and affects later drawings
- Call translate() repeatedly in a loop without reset (it accumulates)
- Assume translate moves existing pixels (it doesn’t)
- Mix transforms across functions without scoping (hard to debug)
- Ignore that translation happens in the current coordinate system
❓ Frequently Asked Questions
save() before translate and restore() after drawing.setTransform(1,0,0,1,0,0) / resetTransform(), or restore a saved state.Next: SVG
Switch from pixels to vectors and learn SVG fundamentals.
4 people found this page helpful
