这是我方便的方案:
给出:
AB
,A
和B
都具有x
和y
坐标width
,到每个角的距离:width / 2
direction
的度数(0向上,90右,180向下等)如何计算角点x
的{{1}}和y
坐标?
1-4
答案 0 :(得分:1)
最后弄清楚了,在线上有很多不同的方式,但没有一种有效。反复试验赢得了胜利。
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)
);
答案 1 :(得分:1)
通过指示Y轴向上,可以简单地解决以下问题:
我们看到每个拐角点都位于AB段周围+/- 90度角处。考虑下图,很容易计算dx
和dy
值(从A或B到每个拐角点):
dx = (W/2).sin(alpha)
dy = (W/2).cos(alpha)
其中alpha
等于90 - direction
。因此,我们可以按照以下代码段编写js代码:
const A = {x: 0, y: 0};
const B = {x: 10, y: 0};
const direction = 90;
const width = 10;
var length = width / 2;
var angle = (90 - direction) * (Math.PI / 180);
var dx = Math.sin(angle) * length;
var dy = Math.cos(angle) * length;
console.log( "bottom left:", {x: A.x - dx, y: A.y + dy} );
console.log( "bottom right:", {x: A.x + dx, y: A.y - dy} );
console.log("---");
console.log( "top left:", {x: B.x - dx, y: B.y + dy} );
console.log( "top right:", {x: B.x + dx, y: B.y - dy} );