Fixed Length Javascript Canvas Curve

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

  • starting point
  • end point
  • curve length

How can I do such a thing, limited by the borders of the canvas, plus the curve cannot intersect. I tried to find some solution, but I can not figure it out. Thank you for your time.

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

This is a quadratic curve drawn on canvas. All perfectly. The question is how to draw this without all the points, only with a fixed length in pixels, random points limited by the size of the canvas and not intersecting.

enter image description here

The code might 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. } } 
+6
source share
1 answer

Try ( 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 uses quadraticCurveTo to draw a quadratic curve, taking two points into account and calculating a random control point from 20 to 100 pixels above the middle of the curve.


If you want a square to have a specific arc length (which sounds like you could from a question), we can do some math . The length of the quadratic arc (parabola) is equal to:

general integral relation for arc length of a function of x

We have an equation, so produce the derivative:

derivative of quadratic

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

solution

So, for specific x1 and x2, we could work out the equivalent values โ€‹โ€‹of u (x), and then the integral.

Drawing a common quadratic point using a control point involves transforming the equation into vertex shape, as you can see on this manual page . It would be wise to repeat the math with this equation for a start and get a new equation for "u" in the right terms.

+7
source

All Articles