假设我知道两点: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};
}
编辑:哇,Stackoverflow是残酷的。如果你愿意,请随意删除这个问题,尽管我认为这对于坚持同一问题的人可能会有所帮助。也许我错了。
无论如何,感谢评论者的帮助。
答案 0 :(得分:9)
我创造了一个利用相应边的比例的小提琴。将变量smallerLen
调整为任意单位,以查看该点在整个线上移动。