random polygon generator

by magneto903

HTML

<canvas id="canvas" width=350 height=350></canvas>

CSS

#canvas {
  border: 2px solid black;
}

JavaScript

var ctx = document.getElementById('canvas').getContext('2d')

function compareNumbers(a, b) {
  return a - b;
}

function compareVectors(a, b) {
  return Math.atan2(a.y, a.x) - Math.atan2(b.y, b.x);
}

var x_coords = [];
var y_coords = [];

var n = 10;

for (var i = 0; i < n; i++) {
  x_coords.push(Math.floor(Math.random() * 150)+200)
  y_coords.push(Math.floor(Math.random() * 150)+200)
}

min_x = x_coords.pop(0)
max_x = x_coords.pop()

min_y = y_coords.pop(0)
max_y = y_coords.pop()

x_coords.sort(compareNumbers)
y_coords.sort(compareNumbers)

chain_1_x = [min_x]
chain_1_y = [min_y]

chain_2_x = [min_x]
chain_2_y = [min_y]

for (var i=0; i < x_coords.length; i+=2) {
	var way = Math.floor(Math.random()*2)
  if (way == 0) {
  	chain_1_x.push(x_coords[i])
    chain_2_x.push(x_coords[i+1])
  } else {
  	chain_1_x.push(x_coords[i+1])
    chain_2_x.push(x_coords[i])
  }
}

for (var i=0; i < y_coords.length; i+=2) {
	var way = Math.floor(Math.random()*2)
  if (way == 0) {
  	chain_1_y.push(y_coords[i])
    chain_2_y.push(y_coords[i+1])
  } else {
  	chain_1_y.push(y_coords[i+1])
    chain_2_y.push(y_coords[i])
  }
}

chain_1_x.push(max_x)
chain_2_x.push(max_x)

chain_1_y.push(max_y)
chain_2_y.push(max_y)

vec_x = []
vec_y = []

for (var i=0; i < chain_1_x.length-1; i++) {
	vec_x.push(chain_1_x[i]-chain_1_x[i+1])
  vec_x.push(chain_2_x[i]-chain_2_x[i+1])
}

for (var i=0; i < chain_1_y.length-1; i++) {
	vec_y.push(chain_1_y[i]-chain_1_y[i+1])
  vec_y.push(chain_2_y[i]-chain_2_y[i+1])
}


console.log(x_coords);
console.log(y_coords);

console.log(chain_1_x);
console.log(chain_2_x);

console.log(chain_1_y);
console.log(chain_2_y);

console.log(vec_x);
console.log(vec_y);

vecs = []

for (var i=0; i < vec_x.length; i++) {
	var vec_y_el = vec_y.pop(Math.floor(Math.random()*vec_y.length))
	vecs.push([vec_x[i], vec_y_el])
}

vecs.sort(compareVectors)

console.log(vecs)

polygon = [vecs[0]]

for (var i=1; i < vecs.length; i++) {
	polygon.push([polygon[i-1][0]+vecs[i][0],...