计算出线在屏幕内的最长坐标
/** * 计算出线在屏幕内的最长坐标 * 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] }