固定长度的Javascript画布曲线

2023-12-23

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

  • 起点
  • 终点
  • 曲线长度

我怎么能做这样的事情受限于画布边界,加上曲线不能交叉。我试图找到一些解决方案,但我无法弄清楚。谢谢你的时间。

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

这是在画布上绘制的二次曲线。一切安好。问题是,如何在没有所有点的情况下绘制它,仅使用固定长度(以像素为单位)、随机点、受画布大小限制且不交叉。

代码可能如下所示:

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

尝试这个 (fiddle http://jsfiddle.net/naeL4/):

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 像素的随机控制点。


如果您希望二次方程具有特定的弧长(这听起来像您可能从问题中得到的),那么我们可以做一些数学题 http://en.wikipedia.org/wiki/Curve_length。二次曲线(抛物线)的弧长为:

我们有方程,所以计算导数:

因此,如果我们将其定义为 u(x),Wolfram alpha 给我们 http://www.wolframalpha.com/input/?i=integrate+sqrt%281%2B%28u%29%5E2%29:

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

使用控制点绘制一般二次方程涉及将方程转换为顶点形式,如您所见本教程页面 http://www.purplemath.com/modules/sqrvertx.htm。明智的做法是从该方程开始重复数学运算,并以正确的项得到“u”的新方程。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

固定长度的Javascript画布曲线 的相关文章

随机推荐