Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Fun question! I've written a custom implementation of dashed lines; you can <a href="http://phrogz.net/tmp/canvas_dashed_line.html" rel="noreferrer">try it out here</a>. I took the route of Adobe Illustrator and allow you to specify an array of dash/gap lengths.</p> <p>For stackoverflow posterity, here's my implementation (slightly altered for s/o line widths):</p> <pre><code>var CP = window.CanvasRenderingContext2D &amp;&amp; CanvasRenderingContext2D.prototype; if (CP &amp;&amp; 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 = dx ? dy/dx : 1e15; var distRemaining = Math.sqrt( dx*dx + dy*dy ); var dashIndex=0, draw=true; while (distRemaining&gt;=0.1){ var dashLength = dashArray[dashIndex++%dashCount]; if (dashLength &gt; distRemaining) dashLength = distRemaining; var xStep = Math.sqrt( dashLength*dashLength / (1 + slope*slope) ); if (dx&lt;0) xStep = -xStep; x += xStep y += slope*xStep; this[draw ? 'lineTo' : 'moveTo'](x,y); distRemaining -= dashLength; draw = !draw; } } } </code></pre> <p>To draw a line from <code>20,150</code> to <code>170,10</code> with dashes that are 30px long followed by a gap of 10px, you would use:</p> <pre><code>myContext.dashedLine(20,150,170,10,[30,10]); </code></pre> <p>To draw alternating dashes and dots, use (for example):</p> <pre><code>myContext.lineCap = 'round'; myContext.lineWidth = 4; // Lines 4px wide, dots of diameter 4 myContext.dashedLine(20,150,170,10,[30,10,0,10]); </code></pre> <p>The "very short" dash length of <code>0</code> combined with the rounded lineCap results in dots along your line.</p> <p><em>If anyone knows of a way to access the current point of a canvas context path, I'd love to know about it, as it would allow me to write this as <code>ctx.dashTo(x,y,dashes)</code> instead of requiring you to re-specify the start point in the method call.</em></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload