2013-03-24 20 views
0

我想在畫布上畫一條線。因此我使用用戶的兩次點擊來定義起點S和終點E如何截斷2點之間的一條線?

ctx.moveTo(sx, sy); 
ctx.lineTo(ex, ey); 

我進一步想。減去一個靜態的上線兩側偏移,如static int offset = 10; 我的問題是:我怎麼能知道到我有哪個方向(北,東,南,西)添加或減去偏移量?

如果該行從上到下,我將不得不在起始點S上應用(0, +10),並在終點上應用(0, -10)。當線在對角線上穿過座標空間時變得複雜。

也許這可能是一個「簡單」的數學問題,但我錯過了正確的關鍵字來尋找任何解決方案。

+0

查找Math.tan() – Breavyn 2013-03-24 00:53:37

回答

0

你只需要使用一些基本的數學。

  1. 找到x和y位移
  2. 找到θ角
  3. 創建位移矢量
  4. 添加或從你的觀點藉此

讓我知道這不工作。

int offset = 10; 

int[] point1 = {15, 25}; //start point 
int[] point2 = {42, 37}; //end point 

int xDisplacement = point2[0] - point1[0]; 
int yDisplacement = point2[1] - point1[1]; 

double theta = Math.toDegrees(Math.atan2(yDisplacement, xDisplacement));   

double[] diplacementVector = {offset*Math.cos(theta), offset*Math.sin(theta)}; 

point1[0] += diplacementVector[0]; 
point1[1] += diplacementVector[1]; 

point2[0] -= diplacementVector[0]; 
point2[1] -= diplacementVector[1]; 
+0

我明白,這讓我走了! – membersound 2013-03-24 01:56:56