简体   繁体   中英

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.

在此输入图像描述

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.
    }
}

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:

x函数弧长的一般积分关系

We have the equation, so work out the derivative:

二次方程的导数

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

解

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM