Piwwoli - 1 month ago 11

Javascript Question

I made a small fiddle: https://jsfiddle.net/ahvonenj/yp0o728h/

You can press left click down to move the red circle and the bezier curve drawn between the two points is updated, but not in a way I would like it to work.

I would like to calculate the control points dynamically, so that the curve looks something like this:

Case A:

Case B:

Case C:

So basically I want the curve to always make a small, "pretty" curve from point A to point B, regardless of how the points are positioned. Drawing a straight line does not look pretty, so I would like to use a bezier curve to make the line slightly curved.

The problem lies in calculating the control points positions. How is that achieved and is there a easy way to do it, as I have seen many applications that seem to use dynamic bezier curves all over the place.

Since code is required to accompany jsfiddle-links, here is the line which currently draws the bezier curve with static control points:

`ctx.bezierCurveTo(20, 100, 200, 100, c2.x, c2.y);`

I am hoping I don't have to do massive calculations to come up with the control point positions.

Answer

Not massive calculations: https://jsfiddle.net/khrismuc/6fjhLkbv/

```
var dx = c2.x - c1.x;
var dy = c2.y - c1.y;
ctx.beginPath();
ctx.moveTo(c1.x, c1.y);
ctx.bezierCurveTo(c1.x + dx * 0.33, c1.y, c1.x + dx * 0.67, c2.y, c2.x, c2.y);
ctx.stroke();
```

If you want them to be angled like that, calculating the control points is slightly more complicated.