Created
November 18, 2017 08:33
-
-
Save sakuro/2bdbd1a748fc5095d3d3445b57c1db91 to your computer and use it in GitHub Desktop.
Random dots and non-random dots
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> | |
<html> | |
<head> | |
<title>Random Plot</title> | |
<style> | |
canvas { border: solid 1px; } | |
th { font-family: monospace; } | |
</style> | |
</head> | |
<body> | |
<table> | |
<tr> | |
<td><canvas id="canvas1" width="400" height="300"></canvas></td> | |
<td><canvas id="canvas2" width="400" height="300"></canvas></td> | |
</tr> | |
</table> | |
<script> | |
'use strict'; | |
const drawRandomDots = (canvasId, num, acceptable = (x, y) => true) => { | |
const canvas = document.getElementById(canvasId); | |
const ctx = canvas.getContext("2d"); | |
ctx.fillStyle = "green"; | |
while (num--) { | |
while (true) { | |
const x = Math.floor(Math.random() * canvas.width); | |
const y = Math.floor(Math.random() * canvas.height); | |
if (acceptable(x, y)) { | |
ctx.beginPath(); | |
ctx.arc(x, y, 3, 0, Math.PI*2, false); | |
ctx.fill(); | |
break; | |
} | |
} | |
} | |
}; | |
const apartAtLeast = (distance) => { | |
const memo = []; | |
return (x, y) => { | |
if (memo.every((e) => Math.hypot(x - e[0], y - e[1]) > distance)) { | |
memo.push([x, y]); | |
return true; | |
} else { | |
return false; | |
} | |
}; | |
}; | |
drawRandomDots("canvas1", 500); | |
drawRandomDots("canvas2", 500, apartAtLeast(10)); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment