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