2017-08-05 118 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时)。 (我只是要重命名x1p1x2p2的清晰度。)

(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等于两个端点的平均值。然后根据上面的公式计算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