Reputation: 1921
I am trying to find (diagonal) center of a 4 points polynome:
I thought it is as simple as this:
But it seems it is not... So how to callculate/find center x/y of it?
Upvotes: 1
Views: 118
Reputation: 15035
Following on from the comments, using the formula from this Wikipedia page:
... you can compute the intersection point of the diagonals, assuming that the polygon is convex (i.e. the diagonals always intersect).
Note that the point indices are different to those of your polygon: the diagonals are between points
1 – 3
and2 – 4
respectively, whereas your polygon points are ordered1 - 2 - 3 - 4
.
Working snippet:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
function line (ax,ay,bx,by) {
ctx.beginPath();
ctx.moveTo(ax,ay);
ctx.lineTo(bx,by);
ctx.stroke();
}
var x1 = 100 ;
var y1 = 100 ;
var x2 = 110 ;
var y2 = 320 ;
var x3 = 400 ;
var y3 = 200 ;
var x4 = 300 ;
var y4 = 100 ;
// Lines
line(x1,y1,x2,y2) ;
line(x2,y2,x3,y3) ;
line(x3,y3,x4,y4) ;
line(x1,y1,x4,y4) ;
// Diagonals
line(x1,y1,x3,y3) ;
line(x4,y4,x2,y2) ;
var div = (x1-x3)*(y2-y4)-(y1-y3)*(x2-x4) ;
var divx = (x1*y3-y1*x3)*(x2-x4) - (x1-x3)*(x2*y4-y2*x4) ;
var divy = (x1*y3-y1*x3)*(y2-y4) - (y1-y3)*(x2*y4-y2*x4) ;
var x = divx/div ;
var y = divy/div ;
$("#x").val(x) ;
$("#y").val(y) ;
// Center
line(x,y-10,x,y+10) ;
line(x-10,y,x+10,y) ;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="x" disabled />
<input id="y" disabled />
<canvas id="myCanvas" width="800" height="600" style="border:1px solid #d3d3d3;"></canvas>
Upvotes: 1
Reputation: 6169
If you are talking about gravitational center then it will be as following:
G = (A + B + C + D) / 4
means:
xG = (xA + xB + xC + xD) / 4
yG = (yA + yB + yC + yD) / 4
You can see here: Geometric centroid
Upvotes: 2