Skip to content

Instantly share code, notes, and snippets.

@ilshad
Created May 9, 2012 13:45
Show Gist options
  • Save ilshad/2644595 to your computer and use it in GitHub Desktop.
Save ilshad/2644595 to your computer and use it in GitHub Desktop.
HTML5 dashed line implementation
var CP = window.CanvasRenderingContext2D && CanvasRenderingContext2D.prototype;
if (CP && CP.lineTo) {
CP.dashedLine = function (x, y, x2, y2, dashArray) {
this.moveTo(x, y);
if (!dashArray)
dashArray = [10,5];
var dashCount = dashArray.length,
dx = (x2-x),
dy = (y2-y),
slope = (dx != 0) ? dy/dx : dy,
distRemaining = Math.sqrt(dx*dx + dy*dy),
dashIndex = 0,
draw = true;
while (distRemaining >= 0.1) {
var dashLength = dashArray[dashIndex ++ % dashCount];
if (dashLength > distRemaining)
dashLength = distRemaining;
var xStep = Math.sqrt(dashLength * dashLength / (1 + slope*slope));
x += xStep
y += slope * xStep;
this[draw ? 'lineTo' : 'moveTo'](x, y);
distRemaining -= dashLength;
draw = !draw;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment