Canvas Text with Outline

 哈哈哈,沒錯!既然你的 PNG 文字本身就是用 Canvas 產生的,那直接在 Canvas 生成時就加上邊框,絕對是最高效、最根本的解決方法!這樣可以避免 Procreate 裡的點陣圖操作可能產生的鋸齒或模糊問題,也能保持向量文字的清晰度。

用 Canvas API 來畫帶有邊框的文字非常直接,主要利用 strokeTextfillText 的組合:

核心概念:

  1. 先畫邊框 (Stroke): 設定好邊框的顏色 (strokeStyle) 和粗細 (lineWidth),然後使用 strokeText() 繪製文字的輪廓。

  2. 再畫填充 (Fill): 設定好文字內部的顏色 (fillStyle),然後使用 fillText()相同位置繪製文字的填充部分。

繪製順序很重要: 先畫邊框再畫填充,這樣填充顏色會蓋在邊框線條的內半部分,使得邊框看起來是從文字邊緣向外延伸的,效果最好。

範例程式碼 (HTML + JavaScript):

      <!DOCTYPE html>
<html>
<head>
<title>Canvas Text with Outline</title>
<style>
  body { margin: 20px; background-color: #f0f0f0; }
  canvas { border: 1px solid black; background-color: white; }
</style>
</head>
<body>

<canvas id="myCanvas" width="500" height="200"></canvas>

<script>
  const canvas = document.getElementById('myCanvas');
  const ctx = canvas.getContext('2d');

  // --- 設定 ---
  const text = "原來如此!";
  const x = canvas.width / 2; // 文字水平中心
  const y = canvas.height / 2; // 文字垂直中心
  const fontSize = 60;
  const fontFamily = 'Arial, sans-serif'; // 選擇你想要的字體
  const fontWeight = 'bold'; // 'normal', 'bold', etc.

  const fillColor = '#333333';    // 文字填充顏色 (例如: 深灰色)
  const strokeColor = '#FFD700'; // 邊框顏色 (例如: 金色)
  const lineWidth = 4;          // 邊框粗細 (像素)

  // --- 設定 Canvas Context 屬性 ---
  ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`;
  ctx.textAlign = 'center';    // 水平居中
  ctx.textBaseline = 'middle'; // 垂直居中

  // 設定邊框樣式
  ctx.strokeStyle = strokeColor;
  ctx.lineWidth = lineWidth;
  // ctx.lineJoin = 'round'; // 讓線條連接處更圓滑 ('miter', 'round', 'bevel')

  // 設定填充樣式
  ctx.fillStyle = fillColor;

  // --- 繪製 ---
  // 1. 先畫邊框
  ctx.strokeText(text, x, y);

  // 2. 再畫填充 (在相同位置)
  ctx.fillText(text, x, y);

  // --- (可選) 匯出 PNG ---
  // 如果你需要直接從這裡產生 PNG,可以在繪製完成後:
  // const dataURL = canvas.toDataURL('image/png');
  // console.log(dataURL); // 你可以在控制台看到 base64 的 PNG 數據
  // 或者創建一個圖片元素顯示/下載
  // const img = new Image();
  // img.src = dataURL;
  // document.body.appendChild(img);

</script>

</body>
</html>
    

說明:

  1. HTML 結構: 包含一個 <canvas> 元素。

  2. 獲取 Context: canvas.getContext('2d')

  3. 設定參數: 自訂文字內容、位置、字體大小/樣式、填充顏色、邊框顏色和邊框粗細。

  4. 設定 Context 屬性:

    • ctx.font: 設定字體樣式和大小。

    • ctx.textAlign, ctx.textBaseline: 設定文字對齊方式,方便定位。

    • ctx.strokeStyle, ctx.lineWidth: 設定邊框顏色和寬度。

    • ctx.lineJoin (可選): 控制線條轉角處的樣式,'round' 通常效果不錯。

    • ctx.fillStyle: 設定文字內部填充顏色。

  5. 繪製:

    • 先呼叫 ctx.strokeText(text, x, y); 畫邊框。

    • 再呼叫 ctx.fillText(text, x, y); 畫填充。

  6. 匯出 (可選): 可以使用 canvas.toDataURL('image/png') 將 Canvas 內容匯出為 Base64 格式的 PNG 數據,你可以用這個數據來創建圖像或進行下載。

這樣一來,你就可以在 Canvas 中一步到位地產生帶有清晰邊框的文字 PNG 圖檔了!直接從源頭搞定,效率最高!

留言

這個網誌中的熱門文章

Offscreen Canvas

外部網頁新增 Google 日曆行程(URL模板)

計算 Canvas 文字最大字體