Javascript canvas curve with fixed length

我与影子孤独终老i 提交于 2019-12-04 05:25:48

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.

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