JavaScript Area of Irregular Polygon Algorithm
In this script, we will get the Area of an Irregular Polygon, using our Make Anti-alias (Almost) Lines script as the core of line drawing. For line drawing, there's Bresenham's Line Algorithm and then there's everything else. Here's a nice polygon maker based on our NON-Bresenham line maker, which in turn is based on figuring out the hypotenuse of a triangle formed from using two given points as vertices and assuming the 90-degree angle vertices is not found at either point. These will be opposite ends of our line, a.k.a. our hypotenuse.
The hypotenuse formula is one all high school students recognize—getting the square root of the sum of the squares of two adjacent sides. Of course, we are referring to right triangles only. Feel free to use the Make Anti-alias (Almost) Lines Using Bresenham's Line Algorithm instead. Anyway, the area of the shape you draw will be expressed in "square pixels", so if each pixel is a foot, then the number is in feet, but if each 12 pixels is a foot, divide the area number by 144 to get square feet.
JavaScript Charts, Graphs, Graphics, Circles, Ellipses, Arcs, Lines, and Polygons
Grab and Drop, Not Drag and Drop
Add Ids and onClicks to Divs
Add Ids and onClicks and Grab and Drop to Divs
Make Anti-alias (Almost) Lines
Make Anti-alias (Almost) Lines Using Bresenham's Line Algorithm
Good JavaScript Circle Algorithm
Good JavaScript Ellipse Algorithm
Good JavaScript Arc Algorithm
Make JavaScript Irregular Polygon
JavaScript Area of Irregular Polygon Algorithm
Make Line Chart from User-Inputted Data
Make Line Chart from CSV Data
Make Line Chart from MySQL Table Data
Make Bar Chart from User-Inputted Data
Make Bar Chart from CSV Data
Make Bar Chart from MySQL Table Data
Make Pie Chart from User-Inputted Data
Make Pie Chart from CSV Data
Make Pie Chart from MySQL Table Data
Area of Irregular Polygon—first create polygon
Area of Irregular Polygon with area in pixels shown
The onscreen instructions say it all: CLICK MOUSE, MOVE MOUSE, THEN CLICKS MAKE LINES. PRESS ANY KEY FOR COMPLETION OF SHAPE WHEN CURSOR IS NEAR STARTING POINT FOR FINAL CLICK. GET AREA. It makes no difference how many lines or how long they are. Once your shape is done, press any key to see the area of the polygon in pixels. Browsers may balk once there are over 135,000 divs on the screen, but the chances of that happening are very remote since you are very unlikely to draw a polygon with hundreds of lines in it. Divs are used for each of the points in each of the lines, so once the number of points in all your polygon lines add up to around 135,000 you will not be able to go on or get the area, but since you'd have to do over 700 lines 100 pixels long to get such a total, you can ignore this limitation. So you can see how line point divs could add up to 5 or 10 thousand pretty fast, but not 135,000—the IE8 limit. What is this program good for? Nothing but getting polygon areas. Feel free to try 1x1, 2x2, 3x3, or other sizes of line points, by finding CSS styles width:4px and height:4px and changing them, and change background-color:#a4a4a4; to black, red, or whatever, if you like.
On to the script. First, after a few JavaScript variable declarations, including the arrays xdata[] and ydata[] which store vertices, we have function startmouse() {document.onmousemove=getCoords; document.onclick=line; document.onkeypress=thearea;}. The startmouse() function is run by the onload event in the body tag. Notice how we are registering event handlers. We do not use () after them, as that is not how you register event handlers. So, first we assert that the onmousemove event will run the getCoords() function. We need the mouse coordinates to always be known by the script, to make it work right. Next, we run the line() function when the left mouse button is clicked. Finally, we run the thearea function when a key is pressed. This is for getting the polygon area and—if you wish—restarting.
The getCoords() function itself is mostly the standard coordinate reader, which uses different properties depending on the browser, but instead of browser sniffing we check for object support. The clientX event attribute returns the horizontal coordinate (according to the client area) of the mouse pointer when an event was triggered. The client area is the current window. The clientY event attribute returns the vertical coordinate (according to the client area) of the mouse pointer when an event was triggered. The pageX property returns the position of the mouse pointer, relative to the left edge of the document. The pageY property sets or returns the y-coordinate of the mouse pointer relative to the top-left corner of the browser window's client area. The scrollTop property sets or retrieves the number of pixels by which the contents of an object are scrolled upward. The scrollLeft property sets or retrieves the number of pixels by which the contents of an object are scrolled to the left.
The goodline() function uses the Pythagorean theorem equation, which is the 2500-year-old formula for finding the length of the hypotenuse. The Pythagorean equation can be used to solve for a missing side on any right triangle. In the program below, given two points we find the length of the line between two given points. Then a variation on slope-intercept form and point-slope form equations is used to plot each point of the line using 4-pixel-wide colored DIVs with the background-color:#a4a4a4. Although the result is not quite a line with anti-aliased smoothness, this technique is the next best thing. And then we use the innerHTML property, which can be used, as below, to modify your document's HTML on the fly—in this case by slapping a buttload of DIVs on the page. Feel free to use 1-pixel-wide DIVs with the background-color:#000 if you just want a simple line. A wider greyer one is more presentable, in our opinion. Especially for line charts. The lighter the grey, the more it looks anti-aliased—change the color and see for yourself.
In the function line() which is run by left mouse button clicking, if flag is 1 so a click has occurred already, we first save the mouse coordinates into xb and yb. Next we save the former click's mouse position into xa and ya and the current mouse coordinates into the xdata[] and ydata[] arrays—we need these for our area formula. Then we run the goodline() function and draw a line. Then we save the current line coordinates into the saved x and saved y variables xs and ys. If flag is 0, we set it to 1 and simply dump our mouse coordinates into xs and ys and save them also into our arrays, like so: xdata[0]=xs;ydata[0]=ys;. The starting point is one of the polygon vertices, which our area formula will need.
The function thearea() is run by a key press, and it merely sets the flag to 0 and figures the area of the polygon—click for algorithm explanation so you can see the polygon area in a JavaScript alert box, after which a new polygon can be started, if you wish. To do so, answer the question Do another? by clicking on it—it is a link.
The formula is just the old coordinate geometry one updated to JavaScript. Note we insist that the starting point is under 25 pixels away from the ending point before you press a key to get the area. If your cursor is under 25 pixels away in both x and y directions, the figure closes up and the area is shown. Otherwise it waits for your brain cells to percolate a bit more energetically—sooner or later you'll figure out that reading instructions is a good idea! Note that the Math.abs() method returns the absolute value of a number, and we use that since sometimes the area that gets calculated is negative, although still correct. Note that Math is the JavaScript Math Object and abs() is merely a method of this object, so Math.abs() is the correct syntax.
<html>
<head>
<STYLE TYPE="text/css">
.reload {position:absolute;left:700px;top:50px;text-align:center;}
</STYLE>
<script type="text/javascript">
var xa, xb, ya, yb, x, y, yq, xq, ys, xs, flag, startx, starty;
var addtopage;
var xdata = new Array();var ydata = new Array();var n=0;var area=0;var d=0;
function startmouse() {document.onmousemove=getCoords; document.onclick=line; document.onkeypress=thearea;}
function getCoords(e){
if (!e) var e = window.event;
if (e.pageX){xq = e.pageX;yq = e.pageY;} else if
(e.clientX){xq = e.clientX + document.body.scrollLeft;yq = e.clientY + document.body.scrollTop;}}
function goodline(xa, xb, ya, yb) {
var addtopage = "";var linelength = Math.sqrt((xa-xb)*(xa-xb)+(ya-yb)*(ya-yb));
for(var i=0; i<linelength; i++){
x=Math.round(xa+(xb-xa)*i/linelength);
y=Math.round(ya+(yb-ya)*i/linelength);
addtopage += "<div style='position:absolute;left:"+x+"px;top:"+y+"px;background-color:#a4a4a4;width:4px;height:4px;font-size:1px'></div>";}
document.body.innerHTML += addtopage;}
function line(){
if(flag==1){n++;xb=xq;yb=yq;xa=xs;ya=ys;xdata[n]=xq;ydata[n]=yq;goodline(xa, xb, ya, yb);xs=xb;ys=y;}
else{flag=1;xs=xq;ys=yq;startx=xs;starty=ys;xdata[0]=xs;ydata[0]=ys;}}
function thearea(){if(startx<xq+25 && startx>xq-25 && starty<yq+25 && starty>yq-25){flag=0;xb=startx;yb=starty;xa=xs;ya=ys;goodline(xa, xb, ya, yb);area = 0;d = n-1;
for(var v=0;v<n;v++){
area = area + (xdata[d]+xdata[v])*(ydata[d]-ydata[v]);d=v;}
area=Math.abs(area/2);alert(area+" = area in pixels");}}
</script>
</head>
<body onload="startmouse()">
CLICK MOUSE, MOVE MOUSE, THEN CLICKS MAKE LINES. PRESS ANY KEY FOR COMPLETION OF SHAPE WHEN CURSOR IS NEAR STARTING POINT FOR FINAL CLICK. GET AREA.
<div id='b' class='reload'><a HREF="area-of-polygon.html"><B>Do another?</B></a></div>
</body>
</html>