jru*_*rue 10 javascript geometry trigonometry
假设我知道两点:x1,y1和x2,y2.我知道我可以很容易地用毕达哥拉斯计算这条线的长度,但如果我想计算一条缩短版本的线怎么办呢.例如,我希望x,y坐标朝向下一个点10个像素.有没有一个简单的公式来找到一个有角度的线上的任何新点?
好的,这是作为JavaScript函数的解决方案.为了解释的目的,我故意将这个额外的冗长.如下面的评论所示,您必须首先找到角度,然后用新的斜边计算边.

/**
* Calculates length of a line on Cartesian grid, then returns point that is X number of pixels down the line.
*
* @param {Number} fromX - starting x point
* @param {Number} fromY - starting y point
* @param {Number} toX - ending x point for vector
* @param {Number} toY - ending y point for vector
* @param {Number} pxDistance - Number of pixels down line toward ending point to return
* @return {Object} Returns x/y coords of point on line based on number of pixels given
*/
function stortenLineDistance(fromX, fromY, toX, toY, pxDistance){
//if line is vertical
if(fromX === toX)
return {x: toX, y: toY > fromY ? fromY + pxDistance : fromY - pxDistance};
//if line is horizontal
if(fromY === toY)
return {y: toY, x: toX > fromX ? fromX + pxDistance : fromX - pxDistance};
//get each side of original triangle length
var adjacent = toY - fromY;
var opposite = toX - fromX;
var hypotenuse = Math.sqrt(Math.pow(opposite, 2) + Math.pow(adjacent,2));
//find the angle
var angle = Math.acos(adjacent/hypotenuse);
//calculate new opposite and adjacent sides
var newOpposite = Math.sin(angle) * pxDistance;
var newAdjacent = Math.cos(angle) * pxDistance;
//calculate new x/y, see which direction it's going
var y = fromY - newAdjacent,
x = fromX + newOpposite;
return {y: y, x: x};
}
Run Code Online (Sandbox Code Playgroud)
编辑:哇,Stackoverflow是残酷的.如果你愿意,可以随意删除这个问题,不过我觉得这对那些坚持同一问题的人有帮助.也许我错了.
无论如何,感谢评论者的帮助.
| 归档时间: |
|
| 查看次数: |
3531 次 |
| 最近记录: |