Finding Area and Centroid of a Polygon
Based on Formulas from Paul Bourke
And JS Code from Edgar Programmator
When I started drawing a bicycle frame for use in Matter.js, I ran into the problem of finding the center of mass (centroid) of closed polygons because you have to input that as the xy of the polygons you make. In other words, you can make any kind of closed irregular polygon (as long as it is convex) defined by real-world vertices, but Matter will actually position the polygon on the canvas according to an xy that you pass to the Bodies.fromVertices call. That point will be the centroid of the polygon. I have several predefined polygons in the code and you can manually set one of them to "active". Then it will be drawn, with a point to indicate the centroid, and the area and centroid coordinates will be printed to the console. Then you can click in the canvas to define a new polygon. When you press "Go" it will become the active polygon and be drawn with its centroid. "New" clears the canvas.