Canvas Text

What You’ll Learn
Canvas can draw text directly onto the bitmap surface. You can fill text, stroke text, and control alignment/baselines for consistent layout.
Unlike HTML, canvas text does not wrap automatically—you control layout yourself (often using measureText()).
⚡ Quick Reference
ctx.font = '700 32px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = '#2563eb';
ctx.fillText('Hello, Canvas!', canvas.width / 2, canvas.height / 2);fontCSS font string (size + family)
textAlignleft | center | right | start | end
textBaselinetop | middle | alphabetic | bottom…
measureText()Compute width for layout
👀 Live Preview — Font, Align & Outline
Change font size, alignment, and baseline. Toggle filled vs outlined text, and optionally set maxWidth (horizontal scaling only).
Tip: Use measureText() for layout. The maxWidth parameter does not wrap—it compresses text horizontally to fit.
Centered Filled + Stroked Text
This mirrors the legacy example: draw filled text and then an outlined version below it.
<canvas id="myCanvas" width="500" height="220"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.font = '30px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = 'blue';
ctx.strokeStyle = 'black';
ctx.lineWidth = 2;
ctx.fillText('Hello, Canvas!', canvas.width / 2, canvas.height / 2);
ctx.strokeText('Hello, Canvas!', canvas.width / 2, canvas.height / 2 + 50);
</script>Use measureText() for Layout
Measure text width after setting ctx.font and draw a background box that fits.
const text = 'Measured label';
ctx.font = '700 28px Arial';
const w = ctx.measureText(text).width;
const x = 40, y = 70, pad = 14;
ctx.fillStyle = 'rgba(37, 99, 235, 0.18)';
ctx.fillRect(x - pad, y - 28 - pad, w + pad * 2, 40 + pad);
ctx.fillStyle = '#0f172a';
ctx.textAlign = 'left';
ctx.textBaseline = 'alphabetic';
ctx.fillText(text, x, y);💡 Best Practices
Do
- Set
fontbefore callingmeasureText() - Use
textAlign+textBaselinefor predictable positioning - Combine fill + stroke for readable outlined text
- Use consistent font strings (weight + size + family)
- Cache rendered text to an offscreen canvas if drawing it repeatedly
Don’t
- Expect automatic wrapping like HTML (canvas doesn’t wrap)
- Rely on
maxWidthfor wrapping (it compresses horizontally) - Forget that transforms (scale/rotate) also affect text
- Use huge stroke widths on small text (it becomes illegible)
- Redraw complex text every frame without profiling
❓ Frequently Asked Questions
fillText() fills glyphs using fillStyle. strokeText() outlines glyphs using strokeStyle and lineWidth.textAlign='center' and textBaseline='middle', then draw at the canvas center.ctx.measureText(text).width after setting ctx.font.Next: Canvas Transform
Learn how transforms stack and how to combine them cleanly.
4 people found this page helpful
