Created
November 23, 2012 20:20
-
-
Save mrpollo/4137120 to your computer and use it in GitHub Desktop.
Taken from StackOverflow User Frogz - http://stackoverflow.com/users/405017/phrogz - Originally found here: http://stackoverflow.com/a/4577326/610149
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var CP = window.CanvasRenderingContext2D && CanvasRenderingContext2D.prototype; | |
if (CP && CP.lineTo){ | |
CP.dashedLine = function(x,y,x2,y2,dashArray){ | |
if (!dashArray) dashArray=[10,5]; | |
if (dashLength==0) dashLength = 0.001; // Hack for Safari | |
var dashCount = dashArray.length; | |
this.moveTo(x, y); | |
var dx = (x2-x), dy = (y2-y); | |
var slope = dy/dx; | |
var distRemaining = Math.sqrt( dx*dx + dy*dy ); | |
var 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) ); | |
if (dx<0) xStep = -xStep; | |
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