Javascript canvas curve with fixed length

自古美人都是妖i 提交于 2019-12-21 12:32:09

问题


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

回答1:


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:

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.



来源:https://stackoverflow.com/questions/15445260/javascript-canvas-curve-with-fixed-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!