JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="myCanvas" width="500" height="250" style="border:1px solid #000000;"></canvas>
<p>
Initial polygon co-ordinates (bottom left vertex first):
<br>
<br>
<span id="InitialPolygon"></span>
</p>
<p>
Enter new polygon bottom left vertex co-ordinates:
</p>
X co-ord:
<input id="xCord" type="text" size=2 maxlength=2> Y co-ord:
<input id="yCord" type="text" size=2 maxlength=2>
<br>
<br>
<button type="button" onclick="addNewPolygon()">Add New Polygon</button>
<span id="FirstDuplicate"></span>
<span id="DuplicatedVertices"></span>
<body onload="displayPolygonVertices()">
JavaScript
// don't forget to set load type in jsfiddle to no wrap in <body>
// define the global variable and some helper variables to make the code shorter
var gv = {};
gv.o = function(id) {
return document.getElementById(id)
};
gv.i = 'innerHTML';
// initialise the initial and new polygon arrays
var polygon = [
[0, 0],
[1, 0],
[1, -1],
[0, -1]
];
var polygonVertices = [
[null, null],
[null, null],
[null, null],
[null, null]
];
var deletedVertices = [];
var firstDuplicate = null;
// calculate the vertices of a polygon based on one origin vertex
function calculatePolygonVertices(x, y) {
polygonVertices[0][0] = x;
polygonVertices[0][1] = y;
polygonVertices[1][0] = x + 1;
polygonVertices[1][1] = y;
polygonVertices[2][0] = x + 1;
polygonVertices[2][1] = y - 1;
polygonVertices[3][0] = x;
polygonVertices[3][1] = y - 1;
}
// output the polygon vertices to HTML for text display purposes
function displayPolygonVertices() {
var text = "";
var length = polygon.length;
for (var i = 0; i < length; i++) {
text += "(" + polygon[i][0] + ",";
text += polygon[i][1] + ")";
if (i < length - 1) {
text += ", ";
}
}
gv.o("InitialPolygon")[gv.i] = text;
}
// add a new polygon to an existing polygon
function addNewPolygon() {
var x = Number(gv.o("xCord").value);
var y = Number(gv.o("yCord").value);
polygonVertices = [
[null, null],
[null, null],
[null, null],
[null, null]
];
calculatePolygonVertices(x, y);
mergePolygons();
gv.o("FirstDuplicate")[gv.i] = "<br><br>First duplicate vertex of original polygon: " + firstDuplicate;
}
// perform the operations required to merge the current and new polygons into one polygon
function mergePolygons() {
var length = polygon.length;
var newLength = polygonVertices.length;
var duplicates = [];
var duplicatesLength = null;
var diagonalVertex = [];
var duplicatesText = "";
firstDuplicate = null;
// determine which vertices of the new polygon...