检查直线是否与带有 SVG 元素的圆相交

Checking if a line intersects a circle with SVG elements

本文关键字:元素 SVG 是否 检查      更新时间:2023-09-26

我正在尝试用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;
};

我正在使用此堆栈交换评论中概述的方法,但没有得到任何结果。任何人都知道为什么这种方法不起作用?谢谢!

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

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

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