CanvasRenderingContext2D: textBaseline 屬性
Canvas 2D API 的 CanvasRenderingContext2D.textBaseline 屬性指定了繪製文字時使用的當前文字基線。
值
可能的值
"top"-
文字基線是 em 方框的頂部。
"hanging"-
文字基線是懸掛基線。(藏文及其他印度語言文字使用。)
"middle"-
文字基線是 em 方框的中間。
"alphabetic"-
文字基線是正常的 字母基線。預設值。
"ideographic"-
文字基線是表意基線;這是字元主體部分的底部,如果字元的主體部分在字母基線下方向下突出。(漢字、日文和韓文使用。)
"bottom"-
文字基線是邊界框的底部。這與表意基線不同,因為表意基線不考慮下伸部分。
預設值為 "alphabetic"。
示例
屬性值對比
此示例演示了各種 textBaseline 屬性值。
HTML
html
<canvas id="canvas" width="550" height="500"></canvas>
JavaScript
js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const baselines = [
"top",
"hanging",
"middle",
"alphabetic",
"ideographic",
"bottom",
];
ctx.font = "36px serif";
ctx.strokeStyle = "red";
baselines.forEach((baseline, index) => {
ctx.textBaseline = baseline;
const y = 75 + index * 75;
ctx.beginPath();
ctx.moveTo(0, y + 0.5);
ctx.lineTo(550, y + 0.5);
ctx.stroke();
ctx.fillText(`Abcdefghijklmnop (${baseline})`, 0, y);
});
結果
同一行上的屬性值對比
與上一個示例一樣,此示例演示了各種 textBaseline 屬性值,但在本例中,所有這些值都排列在同一行上 — 以便更容易看出它們之間的區別。
HTML
html
<canvas id="canvas" width="724" height="160"></canvas>
JavaScript
js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const baselines = [
"top",
"hanging",
"middle",
"alphabetic",
"ideographic",
"bottom",
];
ctx.font = "20px serif";
ctx.strokeStyle = "red";
ctx.beginPath();
ctx.moveTo(0, 100);
ctx.lineTo(840, 100);
ctx.moveTo(0, 55);
ctx.stroke();
baselines.forEach((baseline, index) => {
ctx.save();
ctx.textBaseline = baseline;
let x = index * 120 + 10;
ctx.fillText("Abcdefghijk", x, 100);
ctx.restore();
ctx.fillText(baseline, x + 5, 50);
});
結果
規範
| 規範 |
|---|
| HTML # dom-context-2d-textbaseline-dev |
瀏覽器相容性
載入中…
另見
- 定義此屬性的介面:
CanvasRenderingContext2D