2017-08-05 3 views
1

私はグラフ理論プロジェクトをやっているので、各エッジの上にエッジの重さを表示する必要があります。P5jsの行の上にテキストを描く

現在、私はこの方法を使用しています:

var x1; //starting point 
var x2; //ending point 


function setup() { 
    createCanvas(640, 480); 
    x1 = createVector(random(0, width/2), random(0, height/2)); //random position to the upper left 
    x2 = createVector(random(width/2, width), random(height/2, height)); //random position to the lower right 
} 

function draw() { 
    background(200); 
    stroke(0); 
    line(x1.x, x1.y, x2.x, x2.y); //draw a line beetween the points 
    d = dist(x1.x, x1.y, x2.x, x2.y); 
    var angle = atan2(x1.y - x2.y, x1.x - x2.x); // gets the angle of the line 
    textAlign(CENTER); 
    text("X1", x1.x + 5, x1.y + 5); // just to show where is the begining 
    text("X2", x2.x - 5, x2.y - 5); // just to show there is the end 
    fill(0); 
    signalx = x1.x > x2.x ? -1 : 1; // if the start is to the right of the end 
    signaly = x1.y > x2.y ? -1 : 1; // if the start is below the end 
    // I think i need to use the angle here 
    text(42, (x1.x + (d/2) * signalx), (x1.y + (d/2) * signaly)); 
} 

問題は予想通りの結果が、十分ではないということです。 current result

アイデアは、テキストは私が示すよということです( 42、エッジの重み)は、ラインの中央より少し上ですが、現在何も起こっていません。

私はラインの角度を考慮する必要があることを知っていますが、どこではわからないのです。

ご協力ありがとうございました。さらに詳しい情報が必要な場合はお知らせください。

答えて

1

あなたがしたいのは、直線補間です。まず、勾配切片形式の線の方程式を見つけます。したがって、yを解くことができます(xを知っているとき)。 (私は明確にするためx1p2p1にとx2の名前を変更するつもりです。)

(math) 
// with points (x1, y1) and (x2, y2) 
y - y1 = m*(x - x1) // point-slope form (just a step) 
y - y1 = m*x - m*x1 
y = m*x - m*x1 + y1 // slope-intercept 

次に、xはラインの中間点であることから、xが2つのエンドポイントの平均に等しいです。上の方程式に基づいてyを計算します。

(code) 
float m = (p2.y - p1.y)/(p2.x - p1.x); 
int x = (x2 + x1)/2; 
int y = m*x - m*p1.x + p1.y; 
+0

多くのおかげで、私はそれが必要でした。私はその中間点(数学から数年離れた場所:D)を計算する方法がわかりませんでした。解決済みとしてマーキングする。 – inblank

+0

それは代数が便利なときです! :P – clabe45

関連する問題