HTML Canvas 文字對齊
HTML Canvas 文字對齊
要對齊 Canvas 中的文字,我們使用兩個屬性
-
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>
自己動手試一試 »
居中文字
示例
在 Canvas 中垂直和水平居中文字
<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>
自己動手試一試 »