繪製文字

在上一章學習瞭如何應用樣式和顏色之後,我們現在將學習如何在畫布上繪製文字。

繪製文字

Canvas 渲染上下文提供了兩種渲染文字的方法:

fillText(text, x, y [, maxWidth])

在指定的 (x,y) 位置填充給定的文字。可選填入最大寬度進行繪製。

strokeText(text, x, y [, maxWidth])

在指定的 (x,y) 位置描繪給定的文字輪廓。可選填入最大寬度進行繪製。

一個 fillText 示例

文字使用當前的 fillStyle 進行填充。

js
function draw() {
  const ctx = document.getElementById("canvas").getContext("2d");
  ctx.font = "48px serif";
  ctx.fillText("Hello world", 10, 50);
}

一個 strokeText 示例

文字使用當前的 strokeStyle 進行填充。

js
function draw() {
  const ctx = document.getElementById("canvas").getContext("2d");
  ctx.font = "48px serif";
  ctx.strokeText("Hello world", 10, 50);
}

文字樣式

在上面的示例中,我們已經使用了 font 屬性來使文字比預設大小稍大一些。還有一些屬性可以讓你調整文字在畫布上的顯示方式。

font = value

繪製文字時使用的當前文字樣式。此字串使用與 CSS font 屬性相同的語法。預設字型為 10px sans-serif。

textAlign = value

文字對齊設定。可能的值:startendleftrightcenter。預設值為 start

textBaseline = value

基線對齊設定。可能的值:tophangingmiddlealphabeticideographicbottom。預設值為 alphabetic

direction = value

方向性。可能的值:ltrrtlinherit。預設值為 inherit

如果你之前使用過 CSS,這些屬性可能對你來說很熟悉。

下面的圖表來自 HTML 規範,演示了 textBaseline 屬性支援的各種基線。

The em-over baseline is roughly at the top of the glyphs in a font, the hanging baseline is where some glyphs like आ are anchored, the middle is half-way between the em-over and em-under baselines, the alphabetic baseline is where characters like Á, ÿ, f, and Ω are anchored, the ideographic-under baseline is where glyphs like 私 and 達 are anchored, and the em-under baseline is roughly at the bottom of the glyphs in a font. The top and bottom of the bounding box can be far from these baselines, due to glyphs extending far outside em-over and em-under baselines.

一個 textBaseline 示例

此示例演示了各種 textBaseline 屬性值。有關更多資訊和詳細示例,請參閱 CanvasRenderingContext2D.textBaseline 頁面。

js
function draw() {
  const ctx = document.getElementById("canvas").getContext("2d");
  ctx.font = "48px serif";

  ctx.textBaseline = "hanging";
  ctx.strokeText("hanging", 10, 50);

  ctx.textBaseline = "middle";
  ctx.strokeText("middle", 250, 50);

  ctx.beginPath();
  ctx.moveTo(10, 50);
  ctx.lineTo(300, 50);
  ctx.stroke();
}

高階文字測量

如果你需要獲取有關文字的更多詳細資訊,以下方法允許你測量它。

measureText()

返回一個 TextMetrics 物件,其中包含指定文字在當前文字樣式下繪製時的畫素寬度。

以下程式碼片段展示瞭如何測量文字並獲取其寬度。

js
function draw() {
  const ctx = document.getElementById("canvas").getContext("2d");
  const text = ctx.measureText("foo"); // TextMetrics object
  text.width; // 16;
}

可訪問性考慮

<canvas> 元素只是一個位圖,不提供關於任何已繪製物件的任何資訊。在畫布上書寫的文字可能會給依賴螢幕放大功能的使用者帶來可讀性問題。畫布元素內的畫素不會縮放,放大時可能會變得模糊。這是因為它們不是向量圖形,而是由畫素組成的字母形狀集合。放大時,畫素會變得更大。

Canvas 內容不會像語義 HTML 那樣暴露給輔助技術。總的來說,你應該避免在可訪問的網站或應用程式中使用 Canvas。替代方案是使用 HTML 元素或 SVG 來代替 Canvas。