求圆和直线之间的交点

求圆和直线之间的交点

/**
 * 求圆和直线之间的交点
 * 直线方程:y = kx + b
 * 圆的方程:(x - m)² + (x - n)² = r²
 * x1, y1 = 线坐标1, x2, y2 = 线坐标2, m, n = 圆坐标, r = 半径
 */
public getInsertPointBetweenCircleAndLine(x1, y1, x2, y2, m, n, r) {
    // console.log(x1, y1, x2, y2, m, n, r)
    let kbArr = this.binaryEquationGetKB(x1, y1, x2, y2)
    let k = kbArr[0]
    let b = kbArr[1]

    let aX = 1 + k * k
    let bX = 2 * k * (b - n) - 2 * m
    let cX = m * m + (b - n) * (b - n) - r * r

    let insertPoints = []
    let xArr = this.quadEquationGetX(aX, bX, cX)
    xArr.forEach(x => {
        let y = k * x + b
        insertPoints.push({ x: x, y: y })
    })
    return insertPoints
}

 

/**
 * 求二元一次方程的系数
 * 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]
}

 

/**
 * 一元二次方程求根
 * ax² + bx + c = 0
 */
public quadEquationGetX(a, b, c) {
    let xArr = []
    let result = Math.pow(b, 2) - 4 * a * c
    if (result > 0) {
        xArr.push((-b + Math.sqrt(result)) / (2 * a))
        xArr.push((-b - Math.sqrt(result)) / (2 * a))
    } else if (result == 0) {
        xArr.push(-b / (2 * a))
    }
    return xArr
}

 

posted @ 2018-12-03 15:12 HaoK 阅读( ...) 评论( ...) 编辑 收藏

你可能感兴趣的:(求圆和直线之间的交点)