javascript - 根据距离和方向计算坐标
问题描述
这是我方便的方案:
鉴于:
- 这是二维的,无需担心第三轴
- Segment
AB
,A
以及B
有x
和y
坐标 - Side
width
,到每个角的距离:width / 2
direction
以度为单位(0 向上,90 向右,180 向下等)
如何计算x
和y
坐标角1-4
?
const A = {x: 0, y: 0};
const B = {x: 10, y: 0};
const direction = 90;
const width = 10;
const halfWidth = width / 2;
// tried the following one that I found but
// no lock, I assume somethings off with angles
function getCorner(point, angle, length) {
return {
x: point.x + Math.cos(angle) * length,
y: point.y + Math.sin(angle) * length
};
}
// EXPECTED
// bottom left: {x: 0, y: 5}
// bottom right: {x: 0, y: -5}
// top left: {x: 10, y: 5}
// top right: {x: 10, y: -5}
console.log(
"bottom left:",
getCorner(A, direction - 90, halfWidth)
);
console.log(
"bottom right:",
getCorner(A, direction + 90, halfWidth)
);
console.log("---");
console.log(
"top left:",
getCorner(B, direction - 90, halfWidth)
);
console.log(
"top right:",
getCorner(B, direction + 90, halfWidth)
);
解决方案
终于弄明白了,网上有这么多不同的方法,没有一个奏效。反复试验赢得了胜利。
const A = {x: 0, y: 0};
const B = {x: 10, y: 0};
const direction = 90;
const width = 10;
const halfWidth = width / 2;
// changed only this function
function getCorner(point, angle, length) {
angle = angle * (Math.PI / 180);
return {
x: point.x + Math.sin(angle) * length,
y: point.y + Math.cos(angle) * length
};
}
// EXPECTED
// bottom left: {x: 0, y: 5}
// bottom right: {x: 0, y: -5}
// top left: {x: 10, y: 5}
// top right: {x: 10, y: -5}
console.log(
"bottom left:",
getCorner(A, direction - 90, halfWidth)
);
// here's an error with JS or something, because
// "x: 6.123233995736766e-16" which is
// "0.0000000000000006123233995736766"
console.log(
"bottom right:",
getCorner(A, direction + 90, halfWidth)
);
console.log("---");
console.log(
"top left:",
getCorner(B, direction - 90, halfWidth)
);
console.log(
"top right:",
getCorner(B, direction + 90, halfWidth)
);
推荐阅读
- python-3.x - Python Zeep:如何获取/检索标头信息:字符集
- java - 如何动态地将多个值添加到 HashMap 中的单个键?
- mysql - MYSQL 触发器中的 CASE 语句
- javascript - 将 JS 对象链接到 HTML div 时遇到问题
- excel - Excel VBA 文本框填充组合框
- mysql - sql - 查找该月的最大分数时如何按月分组?
- javascript - 在 react 上渲染 api 响应数组对象
- c++ - 内存泄漏而不分配任何内存?
- variables - 如何在 VHDL 中初始化具有 n 位数的变量?
- javascript - FullCalendar - 如何为数据库中的每个用户加载计划