PLAYGROUND (experimental)

get_centroid

get_centroid(points)

Return the centroid of a polygon given as a list of points [x0,y0,x1,y1,...].

Syntaxe

var result = get_centroid(points=[x0,y0,x1,y1,...])

Arguments

NameRequiredDefaultDescription
pointsyes-List of points [x0,y0,x1,y1,...]

Full example

canvas(width=650, height=600, center=true,background="#455A64");

var points = [];

var nbpoints = 50;

var r = 200 ;


var colHull = "#D7CCC8";
var colBbox = "#A5D6A7";
var colExt = "#80CBC4";

line(-width(),0,width(),0, stroke="#E3F2FD", weight=.2);
line(0,-height(),0,height(), stroke="#E3F2FD", weight=.2);


load_text_default(20);
text(nbpoints + " random points inside a circle of radius "+r, 0, -height()/2+30, stroke="#FFA726", ax=middle);

for (var i = 0; i < nbpoints; i++) {
    var angle = randfloat(0, TAU);  
    var radius = sqrt(rand()) * r;   
    var x = radius * cos(angle);      
    var y = radius * sin(angle);      
    points.add([x,y]);
}


var hull = polygon_hull(points, draw=false);
polygon(points=hull, stroke=colHull, fill="transparent",weight=10);

var bbox = get_bbox(points);
box(points=bbox, stroke=colBbox, fill="transparent",weight=1);


for (var i = 0; i < length(points); i+=2) {
    var x = points[i];
    var y =  points[i+1];
    circle(x, y, 5, fill="#FF6F00");
}

var colCentroid = "#B39DDB";

var cent = get_centroid(hull);
circle(cent[0], cent[1], 8, fill=colCentroid);


load_text_default(20);


text("Centroid", cent[0]+4, cent[1]-4, stroke=colCentroid);


var near = get_nearest(points, cent);
circle(near[0], near[1], 10, fill="transparent", weight=3, stroke=colExt);

var fur = get_furthest(points, cent);
circle(fur[0], fur[1], 10, fill="transparent", weight=3, stroke=colExt);

load_text_default(16);

var y = -230 ;
var sy = 25;

var x = -320;

text("N=nearest, F=furthest (of centroid)", x, y, stroke=colExt);
y += sy;
text("N-F Distance: "+round(get_distance(fur, near),2), x, y, stroke=colExt);
y += sy;
text("N-F Angle: "+round(get_angle(fur, near),2), x, y, stroke=colExt);
y += sy;
text("F-N Angle: "+round(get_angle(near,fur),2), x, y, stroke=colExt);
var nf=append(fur,near);
polyline(nf, stroke=colExt);

y += sy;
text("Diameter: "+round(get_diameter(points),2), x, y, stroke=colExt);


text("Hull perimeter: "+round(get_perimeter(hull),2), 10,250, stroke=colHull);
text("Hull area: "+round(get_area(hull),2), 10,230, stroke=colHull);


polygon_simplify(hull, 100, stroke="#000", fill="transparent",weight=2);
polygon_smooth(hull, 8, stroke="#F00", fill="transparent",weight=2);

y = height()/2-10;
text("hull, simplified", x, y, stroke="#000");
y -= sy;
text("hull, smoothed", x, y, stroke="#F00");
y -= sy;
text("bounding box", x, y, stroke=colBbox);
y -= sy;
text("convex hull (envelope)", x, y, stroke=colHull);


save("geometry_specials.png");