HTML Canvas 文本对齐
HTML 画布文本对齐
为了在画布上对齐文本,我们使用两个属性
-
textBaseline
- 定义文本的基线(垂直对齐) -
textAlign
- 定义文本的水平对齐
textBaseline 属性
textBaseline
属性定义文本的基线(垂直对齐)。
textBaseline
属性可以具有以下值
- "top"
- "hanging"
- "middle"
- "alphabetic" - 这是默认值
- "ideographic"
- "bottom"
示例
演示 textBaseline
属性的不同值
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// 创建一条线
ctx.strokeStyle = "black";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(0,75);
ctx.lineTo(500,75);
ctx.stroke();
ctx.closePath();
ctx.font = "20px Arial";
ctx.fillStyle = "purple";
ctx.textBaseline = "top";
ctx.fillText("top", 5, 75);
ctx.textBaseline = "hanging";
ctx.fillText("hanging", 40, 75);
ctx.textBaseline = "middle";
ctx.fillText("middle", 120, 75);
ctx.textBaseline = "alphabetic";
ctx.fillText("alphabetic", 190, 75);
ctx.textBaseline = "ideographic";
ctx.fillText("ideographic", 295, 75);
ctx.textBaseline = "bottom";
ctx.fillText("bottom", 410, 75);
</script>
亲自试一试 »
textAlign 属性
textAlign
属性定义文本的水平对齐。
textAlign
属性可以具有以下值
- "left"
- "right"
- "center"
- "start" - 这是默认值
- "end"
示例
演示 textAlign
属性的不同值
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
// 创建一条线
ctx.strokeStyle = "black";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(250,0);
ctx.lineTo(250,250);
ctx.stroke();
ctx.closePath();
ctx.font = "20px Arial";
ctx.fillStyle = "purple";
ctx.textAlign = "center";
ctx.fillText("center", 250, 20);
ctx.textAlign = "start";
ctx.fillText("start", 250, 50);
ctx.textAlign = "end";
ctx.fillText("end", 250, 80);
ctx.textAlign = "left";
ctx.fillText("left", 250, 110);
ctx.textAlign = "right";
ctx.fillText("right", 250, 135);
</script>
亲自试一试 »
居中文本
示例
在画布中垂直和水平居中文本
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.font = "30px Verdana";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("Hello World", canvas.width/2, canvas.height/2);
</script>
亲自试一试 »