Calculate Control Point to Make Your Canvas Curve Hit a Specific Point

Creating curves in HTML5 Canvas is usually achieved with quadraticCurveTo() that has 1 control point or bezierCurveTo() that has 2 control points. In some cases, it might be highly desirable to control the point that the curve hits when drawing with quadraticCurveTo. It is pretty simple, but can be a bit tricky. All it requires, is a little formula that we’ll see in a bit.

Curve with quadraticCurveTo()

This method accepts 4 arguments:

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

  1. x position of control point.
  2. y position of control point.
  3. x position of end of path.
  4. y position of end of path.
context.quadraticCurveTo(cpx, cpy, endx, endy);

Oh, but where goes the startx and starty ? It’s usually specified by moveTo() or the previous call to quadraticCurveTo(). Yeh, you get the idea now. Quick little demo:

Hover over the canvas in the demo above. You’ll see the mouse is positioned at the control points. But what if we want to pass the curve through a specific point ? In our case, this specific point could be the mouse itself.

Formula to Calculate the Control Point

There’s a neat little formula that you can simply memorize or come back here later when you need to lookup. After all, we all believe in “Never remember anything that you can easily lookup”, rite?

A bit of attention required now. Basically, you multiply the co-ordinates of that point by 2 and subtract the average of the start and end points of the curve, from that. Yeh, that’s all! Now, a bit of code for relaxing:

// cpx and cpy are the x/y points through which
// you want to pass the curve.

cpx = cpx * 2 - (x1+x2)/2;
cpy = cpy * 2 - (y1+y2)/2;

Right, that’s the formula and all you need really.

Final Demo

Yessir! Now you see the curve passes through the mouse co-ordinates. But make sure you understand that, the mouse point is not on the control point anymore. That’s the exact reason why I drew red lines – to avoid confusion.

Given this formula, now we can manipulate the hitting point of the curve in any way we want to.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Author: Rishabh

Rishabh is a full stack web and mobile developer from India. Follow me on Twitter.

2 thoughts on “Calculate Control Point to Make Your Canvas Curve Hit a Specific Point”

Leave a Reply

Your email address will not be published. Required fields are marked *