【问题标题】:Checking if a line intersects a circle with SVG elements检查一条线是否与带有 SVG 元素的圆相交
【发布时间】:2015-05-11 03:52:34
【问题描述】:

我正在尝试在 JS 中编写一个给定 SVG 线和圆的函数,它将确定该线是否与该圆相交。但是,我认为由于 SVG 坐标系,我遇到了问题。我写的函数如下:

var inCircle = function(ax, ay, bx, by, cx, cy, r) {

  // put circle at the center to simplify calcs
  ax -= cx; ay -= cy;
  bx -= cx; by -= cy;

  a = ax^2 + ay^2 - r^2;
  b = 2*(ax*(bx - ax) + ay*(by - ay));
  c = (bx - ax)^2 + (by - ay)^2;

  // get discriminant
  disc = b^2 - 4*a*c;

  // check if discriminant has real values
  if(disc <= 0) return false;

  // find intersection points
  sqrtdisc = Math.sqrt(disc);
  t1 = (-b + sqrtdisc)/(2*a);
  t2 = (-b - sqrtdisc)/(2*a);
  if(0 < t1 && t1 < 1 && 0 < t2 && t2 < 1) return true;
  return false;
};

我正在使用stackexchange comment 中列出的方法,但没有得到任何结果。任何人都知道为什么这种方法不起作用?谢谢!

【问题讨论】:

  • 忘记你有这个代码。然后假装这是一个数学问题,并在一张纸上手动解决它。最后将您的解决方案转换为代码。
  • intersection library 可以提供帮助。
  • 感谢@LarsKotthoff,我尝试使用该库中的方法并进行了检查。现在回到我的数学,看看错误在哪里......
  • 在 JavaScript 中,r^2 不提供 r 平方,而是尝试使用 Math.pow(r, 2)。

标签: javascript svg coordinates coordinate-systems


【解决方案1】:

错误在于您以相反的顺序解释了二次方程。试试这个:

c = ax^2 + ay^2 - r^2;
b = 2*(ax*(bx - ax) + ay*(by - ay));
a = (bx - ax)^2 + (by - ay)^2;

然后使用这些定义继续其他计算。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    相关资源
    最近更新 更多