Canvas 文本繪製看似簡單,但字體設置、基線對齊、多行排版、文本測量等細節直接決定視覺效果。本文系統講解 fillText/strokeText 核心 API、字體屬性、對齊基線與實用技巧。
| 方法/屬性 | 說明 |
|---|---|
font | CSS 字體字符串:'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 等同 rightcenter:文本中心對齊 xend:LTR 等同 righttextBaseline 決定文本相對 y 的垂直位置:
alphabetic:默認,字母基線(底部對齊 y)top:頂部對齊 ymiddle:垂直居中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);
document.fonts.ready 等待measureText,緩存測量結果maxWidth 參數會壓縮字形,非等比縮放,慎用Canvas 文本繪製雖無 HTML/CSS 靈活,但在遊戲 UI、數據可視化標註、圖片水印、海報生成等場景不可或缺。掌握基線對齊、測量佈局、多行排版,能讓你駕馭各種文本呈現需求。