Question

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?

Was it helpful?

Solution

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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top