1. 程式人生 > >計算出線在螢幕內的最長座標

計算出線在螢幕內的最長座標

/**
* 計算出線在螢幕內的最長座標
* x1, y1 = 座標1, x2, y2 = 座標2
*/
private createAimLinePosArr(x1: number, y1: number, x2: number, y2: number) {
    let posX, posY;
    if (y2 == y1) y1 += 0.01
    if (x2 == x1) x1 += 0.01

    if (y2 < y1) {
        if (x2 < x1) {
            posX = 0
            posY = this.binaryEquationGetY(x1, y1, x2, y2, posX)
        } 
else { posX = Const.STAGE_WIDTH //最大螢幕寬度 posY = this.binaryEquationGetY(x1, y1, x2, y2, posX) } } else if (y2 > y1) { if (x2 > x1) { posX = Const.STAGE_WIDTH //最大螢幕寬度 posY = this.binaryEquationGetY(x1, y1, x2, y2, posX) }
else { posX = 0 posY = this.binaryEquationGetY(x1, y1, x2, y2, posX) } } if (posY < Const.STAGE_HEIGHT) { if (posY <= 0) { posY = 0 posX = this.binaryEquationGetX(x1, y1, x2, y2, posY) } return [posX, posY] }
else { posY = Const.STAGE_HEIGHT //最大螢幕高度 posX = this.binaryEquationGetX(x1, y1, x2, y2, posY) if (isNaN(posX)) { if (x2 > x1) { posX = Const.STAGE_WIDTH } else { posX = 0 } console.log("posX == NaN", x1, y1, x2, y2, posY) } return [posX, posY] } }

 

/**
 * 二元一次方程:根據x求y
 */
public binaryEquationGetY(x1, y1, x2, y2, x) {
    let kbArr = this.binaryEquationGetKB(x1, y1, x2, y2)
    let k = kbArr[0]
    let b = kbArr[1]
    return k * x + b
}

 

/**
 * 二元一次方程:根據y求x
 */
public binaryEquationGetX(x1, y1, x2, y2, y) {
    let kbArr = this.binaryEquationGetKB(x1, y1, x2, y2)
    let k = kbArr[0]
    let b = kbArr[1]
    return (y - b) / k
}

 

/**
 * 求二元一次方程的係數
 * y1 = k * x1 + b => k = (y1 - b) / x1
 * y2 = k * x2 + b => y2 = ((y1 - b) / x1) * x2 + b
 */
private binaryEquationGetKB(x1, y1, x2, y2) {
    let k = (y1 - y2) / (x1 - x2)
    let b = (x1 * y2 - x2 * y1) / (x1 - x2)
    return [k, b]
}