[英]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個像素的隨機控制點。
如果你希望二次方具有一個特定的弧長(這聽起來像你可能從問題),那么我們可以做一些數學 。 二次曲線(拋物線)的弧長是:
我們有等式,所以計算出衍生物:
因此,如果我們將其定義為u(x), Wolfram alpha會給我們 :
因此對於特定的x1和x2,我們可以計算u(x)的等價值,然后計算積分。
使用控制點繪制一般二次曲線涉及將方程式轉換為頂點形式,如本教程頁面所示 。 明智的做法是用這個等式重復數學,然后用正確的術語得到一個新的'u'等式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.