I need to create a polygon from given set of points, which algorithm should i use for this purpose. The polygon edges should not overlap each other. No. Of ponits can be huge. For example 1000
Asked
Active
Viewed 91 times
1 Answers
2
A simple solution would be to
- compute the barycenter (i.e. the average of x and y of all points)
- sort by angle in respect to the center (i.e.
atan2(p.y-center.y, p.x-center.x)
) - connect the points
The result will be a valid star-shaped polygon with no edge overlapping.
In Javascript for example:
// Generate random points
let pts = [];
for (let i=0; i<100; i++) {
pts.push({x:Math.random()*300,
y:Math.random()*300});
}
// Compute the barycenter
let center = {x:0, y:0};
pts.forEach(p=>{
center.x += p.x;
center.y += p.y;
});
center.x /= pts.length
center.y /= pts.length;
// Sort points on the angle of the
// line connecting to the center
pts.sort((a, b) => Math.atan2(a.y - center.y,
a.x - center.x)
-
Math.atan2(b.y - center.y,
b.x - center.x));
// Draw result
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
canvas.width = canvas.height = 300;
document.body.appendChild(canvas);
ctx.beginPath();
ctx.moveTo(pts[0].x, pts[0].y);
pts.forEach(p=>ctx.lineTo(p.x, p.y));
ctx.fillStyle = "#F00";
ctx.fill();

6502
- 112,025
- 15
- 165
- 265