Canvas Scale

What You’ll Learn
ctx.scale(sx, sy) scales the canvas coordinate system. It doesn’t change the canvas element size—it changes how your drawing commands map to pixels.
Scaling is essential for zooming, responsive drawings, and hi‑DPI (retina) rendering.
⚡ Quick Reference
ctx.scale(scaleX, scaleY);sx1 = no change, 2 = double width
sy0.5 = half height
(0,0)Scaling happens around current origin
lineWidthStrokes get thicker when scaling up
👀 Live Preview — Scale & Stroke Thickness
Change sx and sy and compare the reference rectangle (unscaled) with the scaled one. Toggle whether lineWidth is compensated to keep stroke thickness visually constant.
Tip: If you need pixel-perfect 1px strokes after scaling, you often have to compensate lineWidth and align to half-pixels depending on DPI.
Basic Scaling (Like the Legacy Example)
Draw a rectangle, scale the context, then draw another rectangle to see the size difference.
// Unscaled
ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 100, 50);
// Scale (2x)
ctx.scale(2, 2);
// Scaled
ctx.fillStyle = 'red';
ctx.fillRect(50, 150, 100, 50);Important: scaling is cumulative. Use save()/restore() (or resetTransform) if you don’t want it to affect later drawings.
Scale Around a Point (Center Scaling)
Translate to the scaling center so the shape grows/shrinks around its middle.
const cx = 200, cy = 120;
const w = 120, h = 70;
ctx.save();
ctx.translate(cx, cy);
ctx.scale(1.5, 1.5);
ctx.fillStyle = '#2563eb';
ctx.fillRect(-w / 2, -h / 2, w, h);
ctx.restore();💡 Best Practices
Do
- Use
save()/restore()to scope scaling - Translate to a point before scaling if you want centered scaling
- Remember strokes scale too (plan line widths accordingly)
- Consider devicePixelRatio scaling for crisp rendering on HiDPI screens
- Reset transforms each animation frame before applying new scale
Don’t
- Call
scale()repeatedly without resetting (it multiplies) - Assume scaling changes the canvas element’s CSS size (it doesn’t)
- Forget that text and strokes will be scaled too
- Mix transforms without understanding order (translate/scale order matters)
- Over-scale raster images without expecting blur
❓ Frequently Asked Questions
Next: Canvas Shadow
Add depth using shadowColor, shadowBlur, and offsets.
4 people found this page helpful
