2013-03-16 139 views
6

的Javascript畫布曲線我想提請任何(隨機)曲線,給定:固定長度

  • 起點
  • 終點
  • 曲線長度

我該怎麼辦這種事物受畫布邊界限制,加上曲線不能交叉。我試圖找到一些解決方案,但我無法弄清楚這一點。謝謝你的時間。

這裏是什麼,我想完成更詳細的視圖:

這是二次曲線在畫布上繪製。一切安好。問題是,如何在沒有所有點的情況下繪製這些點,只需要以像素爲單位的固定長度,以畫布大小和非交叉點爲界的隨機點。

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

你有任何部分工作的代碼?我們不只是要神奇地爲你制定一個完整的實施方案。 – 2013-03-16 03:37:05

+1

我不知道如何使用曲線長度來繪製它,就像我想要的那樣。我得到了畫布和JS來畫正常的貝塞爾,但這不會有幫助,最後我認爲是這樣。 – Trouble 2013-03-16 10:30:34

+1

你對哪種曲線感興趣?只有貝齊爾?立方還是二次? – Joni 2013-03-16 10:43:59

回答

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和X 2,我們可以計算出u(x)的等價值,然後求積分。

使用控制點繪製一般二次曲線涉及將該等式轉換爲頂點形式,如您在this tutorial page上所看到的。明智的做法是重複這個方程式的數學開始,並以正確的方式得到一個新的'u'方程。