javascript - 返回两个圆之间的 x,y 交点的 JavaScript 函数?

标签 javascript geometry

enter image description here

我得到了两个圆的(x,y)中心位置及其半径,但我需要使用 JavaScript 找到它们的交点(用红色标记)。

我认为就数学而言最好的解释是 here (两个圆圈的交集),但我不太了解数学,所以我无法实现它。

例如 d = ||P1 - P0|| , 做什么 ||代表?这是否意味着结果数字始终为正数?

还有 P2 = P0 + a ( P1 - P0 )/d ,这里的 P 不是 (10, 50) 吗?但是在 JavaScript 中执行 (10,50)+13 会得到 63,所以它只是忽略了第一个数字,那么会发生什么?结果应该是(23,63)还是?还有 P1-P0 部分或 (40,30)-(10,60),你如何在 JavaScript 中表达?

最佳答案

将网站上的 C 函数翻译成 JavaScript:

function intersection(x0, y0, r0, x1, y1, r1) {
        var a, dx, dy, d, h, rx, ry;
        var x2, y2;

        /* dx and dy are the vertical and horizontal distances between
         * the circle centers.
         */
        dx = x1 - x0;
        dy = y1 - y0;

        /* Determine the straight-line distance between the centers. */
        d = Math.sqrt((dy*dy) + (dx*dx));

        /* Check for solvability. */
        if (d > (r0 + r1)) {
            /* no solution. circles do not intersect. */
            return false;
        }
        if (d < Math.abs(r0 - r1)) {
            /* no solution. one circle is contained in the other */
            return false;
        }

        /* 'point 2' is the point where the line through the circle
         * intersection points crosses the line between the circle
         * centers.  
         */

        /* Determine the distance from point 0 to point 2. */
        a = ((r0*r0) - (r1*r1) + (d*d)) / (2.0 * d) ;

        /* Determine the coordinates of point 2. */
        x2 = x0 + (dx * a/d);
        y2 = y0 + (dy * a/d);

        /* Determine the distance from point 2 to either of the
         * intersection points.
         */
        h = Math.sqrt((r0*r0) - (a*a));

        /* Now determine the offsets of the intersection points from
         * point 2.
         */
        rx = -dy * (h/d);
        ry = dx * (h/d);

        /* Determine the absolute intersection points. */
        var xi = x2 + rx;
        var xi_prime = x2 - rx;
        var yi = y2 + ry;
        var yi_prime = y2 - ry;

        return [xi, xi_prime, yi, yi_prime];
    }

关于javascript - 返回两个圆之间的 x,y 交点的 JavaScript 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12219802/

相关文章:

javascript - 在 ReactJS 中设置状态的条件(三元)运算符

javascript - AJAX insert in MySQL delay - 非插入

javascript - 在文本区域中显示行号

python - 在两个二维物体之间的弹性碰撞中,物体之间的总速度(速度的大小)是否守恒?

python - 在图中查找 3 个节点(或三角形)的循环

javascript - Angular 5-如何向构造函数添加多个参数?

JavaScript 编码风格 : curly brace after multiline condition

c++ - 找到潜在的最大圆

javascript - 每个面有 K 个顶点的 3D 点的三 Angular 剖分

geometry - 关于 BSpline 的问题