js 线段与圆的交点坐标 代码
时间: 2023-05-17 22:03:17 浏览: 189
以下是一个简单的 JavaScript 函数,用于计算线段与圆的交点坐标:
```javascript
function getIntersectionPoint(x1, y1, x2, y2, cx, cy, r) {
// 计算线段的长度
var dx = x2 - x1;
var dy = y2 - y1;
var len = Math.sqrt(dx * dx + dy * dy);
// 计算线段的单位向量
var ux = dx / len;
var uy = dy / len;
// 计算线段起点到圆心的向量
var vx = cx - x1;
var vy = cy - y1;
// 计算投影长度
var dot = ux * vx + uy * vy;
var proj = dot / len;
// 如果投影长度小于 0 或大于线段长度,则没有交点
if (proj < 0 || proj > len) {
return null;
}
// 计算交点坐标
var px = x1 + ux * proj;
var py = y1 + uy * proj;
// 如果交点距离圆心的距离大于半径,则没有交点
var dist = Math.sqrt((px - cx) * (px - cx) + (py - cy) * (py - cy));
if (dist > r) {
return null;
}
// 返回交点坐标
return { x: px, y: py };
}
```
这个函数接受 7 个参数:线段的起点坐标 (x1, y1) 和终点坐标 (x2, y2),以及圆的圆心坐标 (cx, cy) 和半径 r。如果线段与圆有交点,则返回交点坐标,否则返回 null。
例如,要计算线段 (0, 0) 到 (10, 0) 与圆心为 (5, 5)、半径为 3 的圆的交点坐标,可以这样调用函数:
```javascript
var p = getIntersectionPoint(0, 0, 10, 0, 5, 5, 3);
if (p) {
console.log("交点坐标为 (" + p.x + ", " + p.y + ")");
} else {
console.log("线段与圆没有交点");
}
```
输出结果为:
```
交点坐标为 (5, 0)
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)