JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="a" width="150" height="150"></canvas>
<canvas id="b" width="150" height="150"></canvas>
CSS
canvas {
outline: 1px solid black;
margin: 1em;
}
JavaScript
function renderPoly(ctx, poly) {
ctx.lineStyle = "black";
ctx.beginPath();
ctx.moveTo(poly[0].x, poly[0].y);
for(var i=1;i<poly.length;i++) {
ctx.lineTo(poly[i].x, poly[i].y);
}
ctx.closePath();
ctx.stroke();
}
function simplify(poly) {
newPoly = [];
// Start at the first point
currentPoint = poly[0];
newPoly.push(currentPoint);
// Find out the point that we are going to next
nextPoint = poly.getNextPointFrom(currentPoint);
do {
console.log(newPoly);
// Create a segment from where I am now
// to the point I want to get to.
currentSegment = new Segment(currentPoint, nextPoint);
// Find all the intersections between that segment
// and each segment in the other polgon
intersections = currentSegment.selfIntersectWith(poly);
if(intersections.length == 0)
{
// No intersections
// Add the next point to the new polygon we are constructing
newPoly.push(nextPoint);
// move ahead
currentPoint = nextPoint;
// get the next point we are trying to go to
nextPoint = poly.getNextPointFrom(currentPoint);
}
else
{
// Otherwise, we need to find the closest intersection
closestIntersection = intersections[0];
// Add the point of intersection to our new polygon
newPoly.push(closestIntersection.intersectionPoint);
// Set our current point to the intersection point
currentPoint = closestIntersection.intersectionPoint;
// Set the 'destination' point to the *end* point of the segment
// that we intersected with
nextPoint = closestIntersection.endPoint;
}
// keep going until you get back to the point you started at
} while (currentPoint != poly[0] );
// Done
return newPoly;
}
function...