This is the bocoup web log with posts from Al, Boaz, Rick, Sam, Nate, Nick & Pete. You should also make sure to checkout code.bocoup.com, where we keep the finished versions of ideas we kick around here.


Feb 23, 2010

Get Triangle Height in JavaScript

How to find the height of a triangle in JavaScript if you only have the 3 vertexes/points of the triangle.

Assuming that XY are the top of your triangle, and X1Y1, X2Y2 are the other two points, you can find the height of the triangle using Pythagorean theorem. This method works for Isosceles or Equilateral triangles.

  // Pythagorean theorem for isosceles or equilateral triangle 
  var getTriangleHeight = function(x, y, x1, y1, x2, y2){
    var b = Math.sqrt(Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2)) /2;
    var c = Math.sqrt(Math.pow(x1-x,  2) + Math.pow(y1-y,  2));    
    return Math.sqrt((c*c)-(b*b));
  };


Comments:

2 Comments

  1. Brendan
    Posted February 23, 2010 at 3:51 pm | Permalink

    You might already realize this, but you can save two sqrts and two multiplies in that code. Since you know that the contents of the sqrts in b and c will *always* be positive, you can just leave them squared and calculate your answer directly from them:

    var b2 = (Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2)) /4; // note the 4
    var c2 = Math.pow(x1-x, 2) + Math.pow(y1-y, 2);
    return Math.sqrt(c2 – b2);

    You could also probably save some cycles avoiding pow() or rearranging some things, but it wouldn’t really be worth it unless this is called from an inner loop.

    Check out point/line distance algorithms if you’re interested in the general case.

    Great site. Cheers!

  2. Posted March 1, 2010 at 7:12 pm | Permalink

    Thanks Brendan I will check that out and update this later. This is why I love blogging! ;)




Please send your questions to this address or call Bocoup at 617-379-2752
This web page is proudly maintained by Bocoup and hosted by (mt) Media Temple
All code on this website is Open Source