首页 文章

具有固定长度的Javascript画布曲线

提问于
浏览
6

我想绘制任何(随机)曲线,给定:

  • 起点

  • 终点

  • 曲线长度

我怎么能做这样的东西限制画布边界,加上曲线不能交叉 . 我试图找到一些解决方案,但我无法弄明白 . 谢谢你的时间 .

以下是我想要完成的更详细的视图:

这是在画布上绘制的二次曲线 . 一切都好 . 问题是,如何在没有所有点的情况下绘制这个,只需要以像素为单位的固定长度,随机点,以画布大小和非交叉为界 .

enter image description here

代码看起来像这样:

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 回答

  • 7

    试试这个(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();
    

    这是使用 quadraticCurveTo 绘制二次曲线,给定两个点并计算在曲线中点上方20到100个像素的随机控制点 .


    如果你希望二次方具有一个特定的弧长(这听起来像你可能来自问题),那么我们可以do some maths . 二次曲线(抛物线)的弧长是:

    general integral relation for arc length of a function of x

    我们有等式,所以计算出衍生物:

    derivative of quadratic

    所以,如果我们将其定义为u(x),Wolfram alpha gives us

    solution

    因此对于特定的x1和x2,我们可以计算u(x)的等 Value ,然后计算积分 .

    使用控制点绘制一般二次方涉及将方程转换为顶点形式,如this tutorial page所示 . 明智的做法是重复使用该等式开始的数学,并以正确的术语为'u'得到一个新的等式 .

相关问题