萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

Canvas 文本繪製全解析:fillText、strokeText、字體設置與對齊技巧

Canvas 文本繪製看似簡單,但字體設置、基線對齊、多行排版、文本測量等細節直接決定視覺效果。本文系統講解 fillText/strokeText 核心 API、字體屬性、對齊基線與實用技巧。

核心 API

方法/屬性說明
fontCSS 字體字符串:'bold 24px Microsoft YaHei, sans-serif'
textAlign水平對齊:start/end/left/right/center(相對 x 坐標)
textBaseline垂直基線:top/hanging/middle/alphabetic/ideographic/bottom(相對 y 坐標)
fillText(text, x, y, maxWidth?)填充文本,可選最大寬度(超出自動壓縮)
strokeText(text, x, y, maxWidth?)描邊文本
measureText(text)返回 {width, actualBoundingBoxLeft/Right/Ascent/Descent}

基礎示例

<canvas id="canvas" width="500" height="400" style="background: #ffff00"></canvas>

<script>
const ctx = document.getElementById('canvas').getContext('2d');

ctx.font = '40px "Microsoft YaHei", sans-serif';

// 實心文本
ctx.fillStyle = 'red';
ctx.fillText('Hello, Canvas!', 10, 50);

// 空心文本
ctx.strokeStyle = 'blue';
ctx.lineWidth = 2;
ctx.strokeText('Hello, Canvas!', 10, 100);

// 組合:描邊+填充(描邊在外,填充在內)
ctx.fillStyle = 'white';
ctx.strokeStyle = 'black';
ctx.lineWidth = 3;
ctx.fillText('Standout', 10, 160);
ctx.strokeText('Standout', 10, 160);
</script>

對齊與基線深度解析

textAlign 決定文本相對 x 的水平位置:

  • start:默認,LTR 環境等同 left,RTL 等同 right
  • center:文本中心對齊 x
  • end:LTR 等同 right

textBaseline 決定文本相對 y 的垂直位置:

  • alphabetic:默認,字母基線(底部對齊 y)
  • top:頂部對齊 y
  • middle:垂直居中
  • bottom:底部對齊
  • hanging:懸掛基線(天城文等)
  • ideographic:表意文字基線(中文底部)

可視化對照圖

// 繪製基準線輔助理解
ctx.strokeStyle = 'rgba(0,0,0,0.2)';
ctx.beginPath();
ctx.moveTo(0, 100); ctx.lineTo(500, 100); // y=100 基線
ctx.moveTo(250, 0); ctx.lineTo(250, 400); // x=250 中心線
ctx.stroke();

ctx.font = '30px sans-serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = 'black';
ctx.fillText('center + middle', 250, 100); // 完美居中

多行文本排版

Canvas 無原生換行,需手動實現:

function wrapText(ctx, text, x, y, maxWidth, lineHeight) {
  const words = text.split(' ');
  let line = '';
  let lines = [];
  
  for (let word of words) {
    const testLine = line + word + ' ';
    const metrics = ctx.measureText(testLine);
    if (metrics.width > maxWidth && line !== '') {
      lines.push(line);
      line = word + ' ';
    } else {
      line = testLine;
    }
  }
  lines.push(line);
  
  lines.forEach((l, i) => ctx.fillText(l, x, y + i * lineHeight));
  return lines.length * lineHeight;
}

文本測量與精準定位

const text = 'Hello';
const metrics = ctx.measureText(text);
console.log({
  width: metrics.width,                    // 寬度
  actualBoundingBoxLeft: metrics.actualBoundingBoxLeft,   // 實際左邊界
  actualBoundingBoxRight: metrics.actualBoundingBoxRight, // 實際右邊界
  actualBoundingBoxAscent: metrics.actualBoundingBoxAscent, // 上延
  actualBoundingBoxDescent: metrics.actualBoundingBoxDescent // 下延
});
// 實際文本高度 ≈ ascent + descent

進階效果

文本描邊+填充組合(描邊在外)

ctx.lineWidth = 4;
ctx.strokeStyle = 'black';
ctx.fillStyle = 'white';
ctx.strokeText('Stroke + Fill', 50, 50);
ctx.fillText('Stroke + Fill', 50, 50);

文本漸變

const grad = ctx.createLinearGradient(0, 0, 200, 0);
grad.addColorStop(0, 'red');
grad.addColorStop(1, 'blue');
ctx.fillStyle = grad;
ctx.fillText('Gradient Text', 50, 100);

文本陰影


ctx.shadowColor = 'rgba(0,0,0,0.5)';
ctx.shadowBlur = 3;
ctx.shadowOffsetX = 2;
ctx.shadowOffsetY = 2;
ctx.fillText('Shadow', 50, 150);

性能與最佳實踐

  • 字體加載完成前繪製會 fallback,使用 document.fonts.ready 等待
  • 大量文本考慮離屏 Canvas 緩存或 WebGL 文本渲染
  • 避免每幀重複 measureText,緩存測量結果
  • maxWidth 參數會壓縮字形,非等比縮放,慎用

Canvas 文本繪製雖無 HTML/CSS 靈活,但在遊戲 UI、數據可視化標註、圖片水印、海報生成等場景不可或缺。掌握基線對齊、測量佈局、多行排版,能讓你駕馭各種文本呈現需求。

copyright © 萬盛學電腦網 all rights reserved