Search code examples
javascriptcanvaskonvajskonva

how to limit the anchor of bezier curve to stay on the line


how can i limit the anchor of bezier curve line to stay on line..

Requirement

Here is my demo - linkhere is my codepen


Solution

  • Quadratic Bezier curve is defined by a start point, an end point, and a control point. The curve is influenced by the control point, but does not necessarily pass through it.

    However, you can manipulate the control point to make the curve appear to pass through a certain point. Here's how you can do it:

    
    function computeQuadraticBezierPathData(p0, p1, p2) {
      const controlPoint = {
        x: (p1.x * 2) - ((p0.x + p2.x) / 2),
        y: (p1.y * 2) - ((p0.y + p2.y) / 2)
      };
    
      const pathData = `M${p0.x},${p0.y} Q${controlPoint.x},${controlPoint.y} ${p2.x},${p2.y}`;
      return pathData;
    }