Code

Canvas

Text Rendering

Beginner Drawing, styling and measuring text — fillText, strokeText, fonts, alignment, baseline, shadows, and measureText. MDN Reference

// Basic fillText
ctx.font = '32px sans-serif';
ctx.fillStyle = '#1e293b';
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
ctx.fillText('fillText — basic', 20, 10);

// strokeText
ctx.font = 'bold 36px Georgia, serif';
ctx.strokeStyle = '#4f46e5';
ctx.lineWidth = 1.5;
ctx.strokeText('strokeText', 20, 55);

// Gradient fill text
const grad = ctx.createLinearGradient(0, 0, W, 0);
grad.addColorStop(0, '#ec4899');
grad.addColorStop(1, '#f59e0b');
ctx.font = 'bold 40px Arial, sans-serif';
ctx.fillStyle = grad;
ctx.textAlign = 'center';
ctx.fillText('Gradient Text', W / 2, 105);

// textAlign
ctx.textAlign = 'left';   ctx.fillText('left',   W/2, 160);
ctx.textAlign = 'center'; ctx.fillText('center', W/2, 184);
ctx.textAlign = 'right';  ctx.fillText('right',  W/2, 208);

// textBaseline (all drawn at same y)
const baselines = ['top','middle','alphabetic','bottom'];
ctx.textBaseline = bl;
ctx.fillText(bl, x, y);

// measureText
const metrics = ctx.measureText('Hello');
console.log(metrics.width); // pixel width

// Shadow on text
ctx.shadowColor   = 'rgba(99,102,241,0.5)';
ctx.shadowBlur    = 10;
ctx.shadowOffsetX = 3;
ctx.shadowOffsetY = 3;
ctx.fillText('Text with Shadow', 20, 375);
ctx.shadowColor = 'transparent';
Key APIs
  • ctx.font — CSS font shorthand: 'bold 24px Arial'
  • ctx.textAlignleft | center | right | start | end
  • ctx.textBaselinetop | middle | alphabetic | bottom | hanging
  • ctx.fillText(text, x, y, maxWidth?) — filled text
  • ctx.strokeText(text, x, y, maxWidth?) — outlined text
  • ctx.measureText(text) — returns TextMetrics with width, ascent, descent