/* Get area of a polygon/surface */
function area(polygon) {
let total = 0;
for (let i = 0; i < polygon.length; i++) {
const addX = polygon[i][0];
const addY = polygon[i === polygon.length - 1 ? 0 : i + 1][1];
const subX = polygon[i === polygon.length - 1 ? 0 : i + 1][0];
const subY = polygon[i][1];
total += (addX * addY * 0.5) - (subX * subY * 0.5);
}
return Math.abs(total);
}
function drawPolygon(context, polygon, strokeStyle, fillStyle) {
context.strokeStyle = strokeStyle;
context.fillStyle = fillStyle;
context.beginPath();
context.moveTo(polygon[0][0], polygon[0][1]); //first vertex
for (var i = 1; i < polygon.length; i++)
context.lineTo(polygon[i][0], polygon[i][1]);
context.lineTo(polygon[0][0], polygon[0][1]); //back to start
context.fill();
context.stroke();
context.closePath();
}
display = function(n) {
var context = document.getElementById("canvas").getContext("2d");
context.clearRect(0, 0, 500, 500);
drawPolygon(context, polygons[n], "#888", "#88f");
document.querySelector('span').textContent = area(polygons[n]);
};
const polygons = [
[[100, 100], [100, 300], [300, 400], [400, 250], [300, 0]],
[[300, 300], [300, 100], [0, 0], [-100, 400]],
[[50, 150], [200, 50], [350, 150], [350, 250], [250, 320], [200, 250], [150, 350], [100, 250]],
[[100, 100], [300, 100], [400, 300], [100, 300]]
];
const buttons = document.querySelectorAll("button");
for (let counter = 0; counter < buttons.length; counter++) {
buttons[counter].addEventListener("click", function(){
window.onload = display(counter);
});
}
window.onload = display(0);
<button onclick="display(0)">Polygon 0</button>
<button onclick="display(1)">Polygon 1</button>
<button onclick="display(2)">Polygon 2</button>
<button onclick="display(3)">Polygon 3</button>
Polygon area : <span id='area'></span>
<canvas id='canvas' width='400' height='400'></canvas>