Search code examples
javascriptsvgsnap.svg

Snap.svg APIs to help find the intersection point of a line and a quadratic curve


How to find the intersection point of a line and a quadratic curve?

Here is the code to generate the figure of choice:

  var s = Snap(300, 300);

  var path = s.path("M 35 50 h 100 v 50 q -25 -20 -50 0 q -25 20 -50 0 z")

  path.attr({
    fill:'none',
    stroke: 'black'
  });

  var bbox = Snap.path.getBBox(path);
  console.log(bbox);
  var pbox = path.getBBox();
  console.log(pbox);
  s.circle(bbox.x, bbox.y, 3).attr('fill', 'red');
  s.circle(bbox.x2, bbox.y2, 3).attr('fill', 'red');
  s.circle(bbox.cx, bbox.cy, 3).attr('fill', 'magenta');

  var l = s.line(bbox.cx, bbox.cy, 250, 200).attr('stroke', 'black');

  var lbox = l.getBBox();

  console.log(lbox);

The image looks like this:

enter image description here

I am trying to find the point highlighted by the blue circle.

Plunk: http://plnkr.co/edit/ZFo381tZfG4SHWHKyINZ?p=preview


Solution

  • Snap has a method Snap.path.intersection. So if you can use a path instead of a line, you could use that method. Just be aware that if the paths can change, there may be multiple or no intersections, so you may want to loop through the intersections, rather than just taking the first.

    Changed bits of code...

    var l = s.path('M'+bbox.cx+','+bbox.cy+'L250,200').attr({ stroke: 'black'}) 
    var intersection = Snap.path.intersection( path.attr('d'), l.attr('d')) 
    s.circle( intersection[0].x, intersection[0].y,5 )
    

    example