Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript canvas curve with fixed length

I want to draw any ( randomized ) curve, with given:

  • start point
  • end point
  • curve length

How can I do such a thing limited by canvas boundaries, plus the curve can not cross. I was trying to find some solution but I can't figure this out. Thanks for your time.

Here is more detailed view of what I want to accomplish:

This is Quadratic curve drawn on canvas. Everything is fine. Question is, how to draw this without all the points, just with the fixed length in pixels, random points, bounded by canvas size and non crossing.

enter image description here

The code could look something like this:

function fixedCurve( A, B, length ){
    for(int i = A; i < B; i++){
        //Calculate random point with propper distance to get first base point, random direction could be calculated before loop.
        //Basicly this loop should calculate integrate of the curve and draw it each step.
    }
}
like image 971
Trouble Avatar asked Mar 16 '13 03:03

Trouble


1 Answers

Try this (fiddle):

function draw() {
  var ctx = document.getElementById('canvas').getContext('2d');

  ctx.fillStyle = "red";

  ctx.beginPath();
  var start = [20, 100];
  var end = [120, 100];
  var above = Math.random()*80+20;
  // find the mid point between the ends, and subtract distance above
  //   from y value (y increases downwards);
  var control = [0.5*(start[0]+end[0]), 0.5*(start[1]+end[1])-above];    
  ctx.moveTo(start[0], start[1]);

  ctx.quadraticCurveTo(control[0], control[1], end[0], end[1]); 
  ctx.stroke();
}

draw();

This is using quadraticCurveTo to draw a quadratic curve, given two points and calculating a random control point 20 to 100 pixels above the midpoint of the curve.


If you want the quadratic to have a specific arc length (which is sounds like you might from the question), then we can do some maths. Arc length of a quadratic (parabola) is:

general integral relation for arc length of a function of x

We have the equation, so work out the derivative:

derivative of quadratic

So if we define this to be u(x), Wolfram alpha gives us:

solution

So for a particular x1 and x2, we could work out the equivalent values of u(x), and then therefore the integral.

Drawing a general quadratic using the control point involves converting the equation to vertex form as you can see on this tutorial page. The sensible thing would be to repeat the maths with that equation to start with, and get a new equation for 'u' in the right terms.

like image 116
Phil H Avatar answered Oct 07 '22 16:10

Phil H