1

Given a set of points, say (10, 10) and (50, 10), how can I plot a curve between them? My geometry is a bit rusty and I'm not sure of which canvas method to use (arc(), quadradicCurveTo(), etc..).

Can anyone point me in the right direction?

ben lemasurier
  • 2,582
  • 4
  • 22
  • 37
  • It depends on what kind of curve you want. Generally a curve is defined by more than two points. – hobberwickey Mar 30 '12 at 17:04
  • @hobberwickey, I guess I'm not sure exactly what type of curve I need. I'd like to fill up as height as possible. e.g. height of canvas = 500, start_x = 0, start_y = 0, end_x = 50, end_y = 0, midpoint_x = 25, midpoint_y = 500; – ben lemasurier Mar 30 '12 at 17:07

1 Answers1

1

Well, there's a lot of different options depending on what you want to curve to look like, but this will basically make the two points part of an ellipse

function curveBetweenPoints(startX, startY, endX, endY, ctx){
    var cp1 = {
        x: startX,
        y: ctx.canvas.height - ((ctx.canvas.height - startY) / 2)
    };

    var cp2 = {
        x: startX + ((endX - startX) / 4),
        y: ctx.canvas.height
    };

    var cp3 = {
       x: endX - ((endX - startX) / 4),
       y: ctx.canvas.height
    }

    var cp4 = {
       x: endX,
       y: ctx.canvas.height - ((ctx.canvas.height - endY) / 2)
    }

    ctx.beginPath();
    ctx.moveTo(startX, startY);
    ctx.bezierCurveTo(cp1.x, cp1.y, cp2.x, cp2.y, (endX - startX) / 2, ctx.canvas.height);
    ctx.bezierCurveTo(cp3.x, cp3.y, cp4.x, cp4.y, endX, endY);
    ctx.stroke();
}
hobberwickey
  • 6,118
  • 4
  • 28
  • 29
  • Tested this in Chrome/Firefox/Safari and it doesn't actually. The midpoint ends up somewhere towards the bottom of the canvas – Geuis Nov 19 '12 at 09:37
  • well, if its an ellipse it should probably be at a midpoint of the maximum radius from the center point. When I ran your code, the line curves up slightly on both ends, then nose dives down and to the left in a kind of squiggle. – Geuis Nov 19 '12 at 23:03
  • Fixed it, now it's a smoother curve, http://jsfiddle.net/e9qAH/2/. It's basically two quarters of two different ellipses stuck together. I don't know the math to make a continuous bezier that fills the available height of the canvas, or a quadratic curve that intersects two given points in a plane. – hobberwickey Nov 20 '12 at 04:02