0

I work on a project on svg using the SVG.JS plugin. I want to let the circle follow the path, when dragged

1 Answers1

0

Interesting question. I created a fiddle for you which shows the functionality you want: https://jsfiddle.net/4ac7o8r6/18/

I used the draggable plugin with a constraint function. Normally this function returns a constraint box or a boolean which decides wether something is dragged or not. I always return false and move the circle myself:

var canvas = SVG('container')

var path = canvas.path('M200,300 Q400,50 600,300 T1000,300').stroke('black').x(10).fill('none')
var length = path.length()

var circle = canvas.circle(20).draggable(function(x, y) {

  var p = getPointAtX(x)

  circle.center(p.x, p.y)

  return false

})

I then define a function which returns the point on a path for a given x. I have to do this by approximation because there is no function to do that. I do it with nested intervals:

var start = path.node.getPointAtLength(0)
circle.center(start.x, start.y)

var precision = 1/length

function getPointAtX(x) {

  var p, pos = 0.5, interval = pos/2

    while(p = path.node.getPointAtLength(pos*length)) {

    if(p.x > x) {
        pos -= interval
    } else {
      pos += interval
    }

    interval /= 2

    // should be one pixel
    if(interval < precision) break
  }

  return p
}

And voila the circle moves on the path when dragging. Quite nice isnt it?

Fuzzyma
  • 7,619
  • 6
  • 28
  • 60