svg.draw.js: .draw() usage is ambiguous

.draw() usage is ambiguous. Take the following code snippet:

const drawing = SVG('mua_logo')

drawing.on('dblclick', event => {
	/* not working - click events are not handled */
	//const line = drawing.polyline().draw(event)

	const line = drawing.polyline().draw()
	line.draw(event)
})

_live example: https://github.com/dotnetCarpenter/mua_

I’m not sure why, but if I do drawing.polyline().draw(event) as oppose to drawing.polyline().draw().draw(event), the click event is no longer handled by svg.draw.js.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 15 (15 by maintainers)

Commits related to this issue

Most upvoted comments

Ok I try to explain the whole thing again: When you call draw() with no parameter, it binds to the click event by default. However that means that it starts the drawing process when you click somewhere and not before. So when you want to set a point you need to do that manually by calling draw('point', event) or draw.event().

When you do not want to bind click by default you need to pass an event argument which is instead used to start teh drawing process. However that means, that you need to manage the whole drawing process yourself. The plugin wont take over again.

So in your case: You want to start the drawing process on dblclick but after that you want to use click so you have 2 possibilities

  • the one discussed above with setting the first point manually but letting draw() bind to click by default
  • you manage everything alone - and that would kinda look like this:
var dblclickHandler = function(ev) {
  // dont start another drawing when oldone isnt finished yet
  canvas.off('dblclick', dblclickHandler)

  // start drawing process. dont bind to default click. draw first point
  var line = canvas.polyline().draw(ev).stroke('black')
  
  // bind to click and draw a point on every click
  var clickHandler = function clickHandler(ev) {
    line.draw('point', ev) // or line.draw(ev)
  }
  canvas.on('click', clickHandler)
  
  // wait for enter keydown and finish shape. unbind/bind events
  SVG.on(document, 'keydown', function keydownHandler(ev){
    // finished by enter
    if(ev.keyCode == '13') {
      line.draw('done')
      SVG.off(document, 'keydown', keydownHandler)
      canvas.off('click', clickHandler)
      canvas.on('dblclick', dblclickHandler)
    }
  })
}

canvas.on('dblclick', dblclickHandler)

Thats tested - it works. However - if you want to use click for points is easier to use the magic default bind. Hope its clear now how this all works. You have to manage the drawing process yourself entirely when you want control. The defaul click handler is just a bonus and for new people to have a result immidiately

I think this is a prime example! and something that should be in the readme. I might make a PR, if I find time and the right words. Thanks a lot!