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
interval 為步進。arc),並 fill 填滿形成實心圓點。此法簡潔高效,適合簡報、圖表輔助線等場景。若需斜線,可引入向量數學計算角度與步進向量。