Last active
December 30, 2016 22:26
-
-
Save darshit-shah/1191abd5253c68ac615218d24e978475 to your computer and use it in GitHub Desktop.
Generate Convex Polygons
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<canvas width="500" height="500"></canvas> | |
<script> | |
var canvas = document.querySelector("canvas"), | |
context = canvas.getContext("2d"); | |
var width = canvas.width, | |
height = canvas.height; | |
var counter=0; | |
var startTime = new Date().getTime(); | |
function generate(){ | |
while(true){ | |
var r = 200; | |
var cx = 250; | |
var cy = 250; | |
var pointPoolCount = 120 + Math.ceil(Math.random()*120); | |
var pointPool = new Array(pointPoolCount); | |
for (var i = 0, n = pointPoolCount; i < n; ++i) { | |
var a = (i*2*Math.PI)/pointPoolCount; | |
pointPool[i] = [cx + r * Math.cos(a), cy + r * Math.sin(a)]; | |
} | |
var n = 10 + Math.floor(Math.random()*3); | |
var points = new Array(n); | |
var bucket = Math.floor(pointPoolCount/n); | |
for (var i = 0; i < n; i++) { | |
points[i] = pointPool[(i*bucket)+Math.floor(Math.random()*bucket)]; | |
} | |
counter++; | |
if(counter%25000 === 0){ | |
break; | |
} | |
} | |
console.log(counter + " in "+ Math.floor((new Date().getTime()-startTime)/1000)+" Seconds. Avg "+Math.ceil(counter/((new Date().getTime()-startTime)/1000))+"/sec."); | |
context.clearRect(0, 0, width, height); | |
context.font = "24px Arial"; | |
context.fillStyle = "black"; | |
context.lineWidth = 1; | |
context.strokeStyle = "BLACK"; | |
context.fillText(counter + " in "+ Math.floor((new Date().getTime()-startTime)/1000)+" Seconds. Avg "+Math.ceil(counter/((new Date().getTime()-startTime)/1000))+"/sec.",10,20); | |
context.closePath(); | |
context.beginPath(); | |
context.moveTo(points[0][0], points[0][1]); | |
for (var i = 1; i < n ; i++) { | |
context.lineTo(points[i][0], points[i][1]); | |
} | |
context.closePath(); | |
context.fillStyle = "steelblue"; | |
context.fill(); | |
context.lineWidth = 2; | |
context.lineJoin = "round"; | |
context.strokeStyle = "steelblue"; | |
context.stroke(); | |
setTimeout(generate,1); | |
} | |
generate(); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment