Canvas textBaseline属性详解,掌握top、bottom、middle、alphabetic等基线对齐方式。textBaseline属性控制文本的垂直对齐方式,决定文本相对于绘制坐标的垂直位置。
ctx.textBaseline = 'top' | 'hanging' | 'middle' | 'alphabetic' | 'ideographic' | 'bottom'
| 值 | 说明 |
|---|---|
| top | 文本顶部对齐坐标 |
| hanging | 悬挂基线(主要用于印度文字) |
| middle | 文本中部对齐坐标 |
| alphabetic | 字母基线(默认) |
| ideographic | 表意文字基线 |
| bottom | 文本底部对齐坐标 |
// top: 坐标在文本顶部
ctx.textBaseline = 'top'
ctx.fillText('文本', 50, 50) // 文本从y=50开始向下
// middle: 坐标在文本中部
ctx.textBaseline = 'middle'
ctx.fillText('文本', 50, 50) // 文本以y=50为中心
// bottom: 坐标在文本底部
ctx.textBaseline = 'bottom'
ctx.fillText('文本', 50, 50) // 文本在y=50上方结束
默认值
textBaseline默认值为'alphabetic'。
与textAlign配合
通常需要同时设置textAlign和textBaseline实现精确对齐。
字体差异
不同字体的基线位置可能略有差异。