13

I'm tasked to do cropping in canvas and i'm finished with all the logic but one requirement is yet to be finished i.e to draw a dashed rectangle while selecting cropping area like:

strokeRect(x, y, width, height)

How can I draw a dashed rectangle?

Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
user1070642
  • 273
  • 1
  • 5
  • 15
  • It's not straightforward. Refer to: http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas – RSG Dec 30 '11 at 08:28
  • Look at this question: http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas – techfoobar Dec 30 '11 at 08:32

3 Answers3

23

This has been added to the canvas spec, not all browsers have implemented it yet, but here it is.

context.setLineDash([6]);
context.strokeRect(0, 0, 50, 50);
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
Paul Milham
  • 526
  • 5
  • 13
1

There's no built in functionality for dashed lines, but here's an example using a custom JS prototype:

HTML5 Canvas and Dashed Lines

Clay Garrett
  • 1,023
  • 8
  • 11
1

Refer : dotted stroke in <canvas>

 var CP = window.CanvasRenderingContext2D && CanvasRenderingContext2D.prototype;
    if (CP && CP.lineTo){
      CP.dashedLine = function(x,y,x2,y2,dashArray){
        if (!dashArray) dashArray=[10,5];
        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) );
          x += xStep
          y += slope*xStep;
          this[draw ? 'lineTo' : 'moveTo'](x,y);
          distRemaining -= dashLength;
          draw = !draw;
        }
      }
    }
Community
  • 1
  • 1