繁体   English   中英

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

[英]Javascript canvas curve with fixed length

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

  • 起点
  • 终点
  • 曲线长度

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

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

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

在此输入图像描述

代码看起来像这样:

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

试试这个( 小提琴 ):

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


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

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

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

二次方程的导数

因此,如果我们将其定义为u(x), Wolfram alpha会给我们

解

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

使用控制点绘制一般二次曲线涉及将方程式转换为顶点形式,如本教程页面所示 明智的做法是用这个等式重复数学,然后用正确的术语得到一个新的'u'等式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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