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:
xposition of control point.
yposition of control point.
xposition of end of path.
yposition 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.
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.