简体   繁体   English

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

[英]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. 这是使用quadraticCurveTo绘制二次曲线,给定两个点并计算在曲线中点上方20到100个像素的随机控制点。


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 : 因此,如果我们将其定义为u(x), Wolfram alpha会给我们

解

So for a particular x1 and x2, we could work out the equivalent values of u(x), and then therefore the integral. 因此对于特定的x1和x2,我们可以计算u(x)的等价值,然后计算积分。

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. 明智的做法是用这个等式重复数学,然后用正确的术语得到一个新的'u'等式。

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

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