按比例調整邊框粗細

 你說得完全正確!邊框的粗細(lineWidth)根據字體大小(fontSize)來調整通常是更合適、視覺效果更均衡的做法。

原因如下:

  1. 視覺比例一致性: 一個固定粗細的邊框,在小字上會顯得特別粗,甚至可能糊掉文字細節;而在大字上則可能顯得太細,失去邊框應有的視覺份量。讓邊框粗細隨字體大小縮放,可以保持邊框和文字本身視覺上的相對比例,看起來更協調。

  2. 可讀性: 對於小字號,太粗的邊框會影響文字的清晰度和辨識度。而對於大字號,太細的邊框可能無法有效區分文字和背景。

  3. 美觀: 按比例縮放的邊框通常在不同尺寸下都更美觀。

如何在 Canvas 中實現?

你可以將 lineWidth 設定為 fontSize 的一個比例值。這個比例需要根據你的喜好和具體字體來調整,通常在 0.050.1 (即 5% 到 10%) 之間是個不錯的起點。

修改後的範例程式碼:

      // --- 設定 ---
  const text = "原來如此!";
  const x = canvas.width / 2;
  const y = canvas.height / 2;
  const fontSize = 60; // 主要的字體大小
  const fontFamily = 'Arial, sans-serif';
  const fontWeight = 'bold';

  const fillColor = '#333333';
  const strokeColor = '#FFD700';

  // *** 根據字體大小計算邊框粗細 ***
  const lineWidthRatio = 0.08; // 邊框粗細比例 (例如 8%)
  const lineWidth = fontSize * lineWidthRatio;
  // (可選) 設定最小/最大粗細,避免極端情況
  // const minLineWidth = 1;
  // const maxLineWidth = 10;
  // const lineWidth = Math.max(minLineWidth, Math.min(maxLineWidth, fontSize * lineWidthRatio));


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

  // 使用計算出的 lineWidth
  ctx.strokeStyle = strokeColor;
  ctx.lineWidth = lineWidth; // 使用計算出的值
  ctx.lineJoin = 'round'; // 推薦使用 round 讓邊角更平滑

  ctx.fillStyle = fillColor;

  // --- 繪製 ---
  ctx.strokeText(text, x, y);
  ctx.fillText(text, x, y);
    

重點:

  • const lineWidthRatio = 0.08;:定義一個比例。

  • const lineWidth = fontSize * lineWidthRatio;:根據字體大小計算實際的邊框粗細。

  • 可選的最小/最大值限制: 使用 Math.max()Math.min() 可以確保邊框不會太細或太粗,尤其是在字體大小變化範圍很大的情況下。

這樣修改後,當你改變 fontSize 時,lineWidth 也會自動按比例調整,使得文字邊框在各種大小下看起來都比較合適。你完全可以根據你的設計需求來調整 lineWidthRatio 這個比例值。

留言

這個網誌中的熱門文章

Offscreen Canvas

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

計算 Canvas 文字最大字體