0

I have a rectangle, I would like to stroke it with 1px dashed line that is typical of selection objects we see in image editors.

I was researching methods, and was wondering which would be most performant?

  1. Should I draw a recntangle then go through and clear the gaps?
  2. Should I use dashedLine from here to draw for 4 dashed lines? https://stackoverflow.com/a/4577326/1828637
  3. Any other methods?

Thanks

Community
  • 1
  • 1
Noitidart
  • 35,443
  • 37
  • 154
  • 323
  • possible duplicate of [dotted stroke in ](http://stackoverflow.com/questions/4576724/dotted-stroke-in-canvas) – speciesUnknown Jul 14 '15 at 15:33
  • @burton I linked that from my topic, my question is which would be more performant to draw a dashed rectangle, that topic is specific for a line. – Noitidart Jul 14 '15 at 15:34
  • i see, i misread the question, my apologies – speciesUnknown Jul 14 '15 at 15:36
  • no problem thanks @gburton , i could have done better and did update the question to be better phrased – Noitidart Jul 14 '15 at 15:37
  • Any particular reason you're worried about performance? Like, you're going to be doing this a million times? –  Jul 14 '15 at 16:18
  • I'm making a canvas image editor, very simple one, the canvas is the size of all monitors combined so its huge. And the selection dashed rect is drawn as user moves mouse :( thanks @torazaburo for the interest! if you have firefox you can test out my addon from here: https://github.com/Noitidart/NativeShot its not yet enabled fully for OSX yet though. – Noitidart Jul 15 '15 at 03:15

1 Answers1

1

Using context.setLineDash(segments); would be a valid method as it is currently supported by all major browsers.

Read more about it here: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash

FWDekker
  • 1,823
  • 2
  • 20
  • 26
  • Thanks very much Waflix! I notice that the line at width of 1 is really quite thick (it is 2px thick), is it possible to get 1px thick only? – Noitidart Jul 14 '15 at 15:56
  • Oh found it, I have to do `context.trasnlate(0.5,0.5)` thats odd: `context.translate(0.5, 0.5); context.beginPath(); context.setLineDash([5]); context.rect(30,15,100,100); context.stroke();` – Noitidart Jul 14 '15 at 16:00
  • The width of the line is only determined by `context.lineWidth = width;` as far as I know. – FWDekker Jul 15 '15 at 13:33
  • Doing `lineWidth` of 1 or 0 makes it still have thickness of 2 :( But when do the `.translate` by 0.5 it anti aliases it or something so it turns out to be 1px. Heres a codepen demoing it http://codepen.io/Veiovis/pen/qzaei – Noitidart Jul 15 '15 at 15:41
  • 1
    It's the anti-aliasing indeed. Sadly there's no support for turning it off (unless you want to do it [the hard way](http://stackoverflow.com/a/195575/3307872)), but your translation seems to be the best alternative. – FWDekker Jul 15 '15 at 15:53