--- title: CanvasRenderingContext2D.textBaseline slug: Web/API/CanvasRenderingContext2D/textBaseline tags: - Canvas - CanvasRenderingContext2D translation_of: Web/API/CanvasRenderingContext2D/textBaseline ---
CanvasRenderingContext2D.textBaseline 是 Canvas 2D API 描述绘制文本时,当前文本基线的属性。
译者注:决定文字垂直方向的对齐方式。
ctx.textBaseline = "top" || "hanging" || "middle" || "alphabetic" || "ideographic" || "bottom";
有效值:
默认值是 alphabetic。
textBaseline 属性这是一段简单的代码片段,使用 textBaseline 属性设置不同的文本基线。
<canvas id="canvas" width="550" height="500"></canvas>
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(function (baseline, index) {
ctx.textBaseline = baseline;
let 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);
});
<canvas id="canvas" width="550" height="500"></canvas>
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(function (baseline, index) {
ctx.textBaseline = baseline;
let 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);
});
{{ EmbedLiveSample('Playable_code', 700, 550) }}
| Specification | Status | Comment |
|---|---|---|
| {{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-textbaseline", "CanvasRenderingContext2D.textBaseline")}} | {{Spec2('HTML WHATWG')}} |
{{Compat("api.CanvasRenderingContext2D.textBaseline")}}