萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML5 Canvas 繪製圓點虛線實作範例

Stack Overflow 上 Phrogz 分享了一個虛線繪製實作,嚴格說是點劃線。若要畫出如下圖的圓點虛線,該如何處理?

以下提供僅支援水平、垂直方向的圓點虛線實作,斜線部分可參考 Phrogz 或 Rod MacDougall 的簡化版擴充。

核心代碼

var canvasPrototype = window.CanvasRenderingContext2D && CanvasRenderingContext2D.prototype;
canvasPrototype.dottedLine = function(x1, y1, x2, y2, interval) {
  if (!interval) interval = 5;
  var isHorizontal = true;
  if (x1 === x2) isHorizontal = false;
  var len = isHorizontal ? x2 - x1 : y2 - y1;
  this.moveTo(x1, y1);
  var progress = 0;
  while (len > progress) {
    progress += interval;
    if (progress > len) progress = len;
    if (isHorizontal) {
      this.moveTo(x1 + progress, y1);
      this.arc(x1 + progress, y1, 1, 0, 2 * Math.PI, true);
      this.fill();
    } else {
      this.moveTo(x1, y1 + progress);
      this.arc(x1, y1 + progress, 1, 0, 2 * Math.PI, true);
      this.fill();
    }
  }
};

使用方式

在 Canvas 2D 上下文中直接呼叫:

ctx.dottedLine(10, 10, 200, 10, 8); // 水平圓點虛線,間距 8px
ctx.dottedLine(50, 50, 50, 150, 6); // 垂直圓點虛線,間距 6px

原理解析

  1. 判斷線段方向(水平或垂直)。
  2. 計算總長度,以 interval 為步進。
  3. 每步進繪製一個半徑 1px 的圓弧(arc),並 fill 填滿形成實心圓點。
  4. 邊界處理:超過長度時修正為終點座標。

此法簡潔高效,適合簡報、圖表輔助線等場景。若需斜線,可引入向量數學計算角度與步進向量。

copyright © 萬盛學電腦網 all rights reserved