如何使用 JavaScript 检测线段与圆的相交

如何使用 javascript 检测线段与圆的相交

本文详细介绍了如何使用 JavaScript 检测线段与圆是否相交。通过计算线段到圆心的最近距离,并与圆的半径进行比较,可以有效地判断是否存在交点。文章提供了两种实现方法,一种避免了昂贵的平方根运算,另一种则能计算出交点距离。同时,提供了可运行的示例代码,方便读者理解和应用。

线段与圆相交检测的原理

判断线段与圆是否相交,核心在于计算线段到圆心的最短距离。如果这个最短距离小于或等于圆的半径,则线段与圆相交;反之,则不相交。

计算线段到圆心的最短距离,首先需要找到线段上距离圆心最近的点。这个点可以通过向量投影的方式求得。然后,计算圆心到该点的距离,并与圆的半径进行比较。

方法一:避免平方根运算的实现

以下代码展示了如何使用 rayInterceptsCircle 函数判断线段(ray)是否与圆相交,避免使用平方根运算,提高了效率。

立即学习“Java免费学习笔记(深入)”;

function rayInterceptsCircle(ray, circle) {        const dx = ray.p2.x - ray.p1.x;    const dy = ray.p2.y - ray.p1.y;    const u = Math.min(1, Math.max(0, ((circle.x - ray.p1.x) * dx + (circle.y - ray.p1.y) * dy) / (dy * dy + dx * dx)));    const nx = ray.p1.x + dx * u - circle.x;    const ny = ray.p1.y + dy * u - circle.y;        return nx * nx + ny * ny < circle.radius * circle.radius;}

代码解释:

dx 和 dy 分别表示线段在 x 和 y 轴上的分量。u 是一个参数,表示线段上距离 ray.p1 最近的点的位置,它的值被限制在 0 到 1 之间,确保该点在线段上。nx 和 ny 表示圆心到线段上最近点的向量。最后,比较 nx * nx + ny * ny (最近距离的平方) 与 circle.radius * circle.radius (半径的平方)。如果前者小于后者,则表示线段与圆相交。

优点:

避免了平方根运算,性能更高。

缺点:

只能判断是否相交,无法获取交点信息。

方法二:计算交点距离的实现

以下代码展示了如何使用 rayDist2Circle 函数计算线段与圆的交点距离。如果线段与圆不相交,则返回 Infinity。

function rayDist2Circle(ray, circle) {    const dx = ray.p2.x - ray.p1.x;    const dy = ray.p2.y - ray.p1.y;    const vcx = ray.p1.x - circle.x;     const vcy = ray.p1.y - circle.y;    var v =  (vcx * dx +  vcy * dy) * (-2 / Math.hypot(dx, dy));    const dd = v * v - 4 * (vcx * vcx + vcy * vcy - circle.radius * circle.radius);    if (dd <= 0) { return Infinity; }    return  (v - Math.sqrt(dd)) / 2;}

代码解释:

dx 和 dy 分别表示线段在 x 和 y 轴上的分量。vcx 和 vcy 表示线段起点到圆心的向量。v 是一个中间变量,用于简化计算。dd 是判别式,如果小于等于 0,则表示线段与圆不相交,返回 Infinity。最后,计算交点距离并返回。

优点:

可以计算交点距离,获取更详细的相交信息。

缺点:

需要进行平方根运算,性能相对较低。

完整示例代码

以下是一个完整的示例代码,演示了如何使用这两种方法进行线段与圆的相交检测。

Line Circle Intersectioncanvas {  position: absolute;  top: 0px;  left: 0px;}const ctx = canvas.getContext("2d");const TAU = Math.PI * 2;requestAnimationFrame(renderLoop);var W = canvas.width, H = canvas.height;const Point = (x, y) => ({x, y}); const Ray = (p1, p2) => ({p1, p2}); const Circle = (p, radius) => ({x: p.x, y: p.y, radius});function drawRayLeng(ray, len) {  ctx.beginPath();  ctx.lineTo(ray.p1.x, ray.p1.y);  if (len < Infinity) {    const dx = ray.p2.x - ray.p1.x;    const dy = ray.p2.y - ray.p1.y;    const scale = len / Math.hypot(dx, dy);    ctx.lineTo(ray.p1.x + dx * scale , ray.p1.y + dy  * scale);  } else {    ctx.lineTo(ray.p2.x, ray.p2.y);  }  ctx.stroke();}function drawRay(ray) {  ctx.beginPath();  ctx.lineTo(ray.p1.x, ray.p1.y);  ctx.lineTo(ray.p2.x, ray.p2.y);  ctx.stroke();}function drawCircle(circle) {  ctx.beginPath();  ctx.arc(circle.x, circle.y, circle.radius, 0, TAU);  ctx.stroke();}function rayInterceptsCircle(ray, circle) {        const dx = ray.p2.x - ray.p1.x;    const dy = ray.p2.y - ray.p1.y;    const u = Math.min(1, Math.max(0, ((circle.x - ray.p1.x) * dx + (circle.y - ray.p1.y) * dy) / (dy * dy + dx * dx)));    const nx = ray.p1.x + dx * u - circle.x;    const ny = ray.p1.y + dy * u - circle.y;        return nx * nx + ny * ny < circle.radius * circle.radius;}function rayDist2Circle(ray, circle) {    const dx = ray.p2.x - ray.p1.x;    const dy = ray.p2.y - ray.p1.y;    const vcx = ray.p1.x - circle.x;     const vcy = ray.p1.y - circle.y;    var v =  (vcx * dx +  vcy * dy) * (-2 / Math.hypot(dx, dy));    const dd = v * v - 4 * (vcx * vcx + vcy * vcy - circle.radius * circle.radius);    if (dd <= 0) { return Infinity; }    return  (v - Math.sqrt(dd)) / 2;}const mouse  = {x : 0, y : 0}function mouseEvents(e){    mouse.x = e.pageX;    mouse.y = e.pageY;}document.addEventListener("mousemove", mouseEvents);const c1 = Circle(Point(150, 120), 60);const r1 = Ray(Point(0, 50), Point(300, 50));function renderLoop(time) {   ctx.clearRect(0, 0, W, H);   r1.p1.x = c1.x + Math.cos(time / 5000) * 100;   r1.p1.y = c1.y + Math.sin(time / 5000) * 100;   r1.p2.x = mouse.x;   r1.p2.y = mouse.y;   ctx.lineWidth = 0.5;   drawCircle(c1);   drawRay(r1);   ctx.lineWidth = 5;   if (rayInterceptsCircle(r1, c1)) {     ctx.strokeStyle = "red";     drawRayLeng(r1, rayDist2Circle(r1, c1));   } else {     drawRay(r1);   }   ctx.strokeStyle = "black";   requestAnimationFrame(renderLoop);}

使用方法:

将代码保存为 HTML 文件。使用浏览器打开该文件。移动鼠标,观察线段与圆的相交情况。当线段与圆相交时,线段会变为红色,并显示交点。

总结

本文介绍了两种使用 JavaScript 检测线段与圆相交的方法。rayInterceptsCircle 函数通过避免平方根运算,提高了性能,适用于只需要判断是否相交的场景。rayDist2Circle 函数可以计算交点距离,获取更详细的相交信息,适用于需要精确计算交点位置的场景。开发者可以根据实际需求选择合适的方法。

以上就是如何使用 JavaScript 检测线段与圆的相交的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1510236.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月20日 05:50:33
下一篇 2025年12月20日 05:50:43

相关推荐

发表回复

登录后才能评论
关注微信