Skip to content

Instantly share code, notes, and snippets.

@gamblore
Last active December 15, 2015 19:49
Show Gist options
  • Save gamblore/5314569 to your computer and use it in GitHub Desktop.
Save gamblore/5314569 to your computer and use it in GitHub Desktop.
Fun with Voronoi
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js"></script>
<script type="text/javascript">
var points = [];
var colors = [];
function getColor(index) {
r = 50 + ((index * 25) % 255) % 255;
g = 50 + ((index * 3 * 15) % 255) % 255;
b = 50 + ((index * 5 * 25) % 255) % 255;
color = "rgb(" + r + "," + g + "," + b + ")";
return color;
}
function distance(p1, p2) {
xdiff = p1[0] - p2[0];
ydiff = p1[1] - p2[1];
return Math.sqrt(xdiff * xdiff + ydiff * ydiff);
}
function findClosest(points, point) {
var minIndex = 0;
var minDist = distance(points[0], point);
for (var i = 1; i < points.length; i++) {
dist = distance(points[i], point);
if (dist < minDist) {
minDist = dist;
minIndex = i;
}
}
return minIndex;
}
function step() {
var ctx = $('screen').getContext("2d");
var width = $('screen').width;
var height = $('screen').height;
console.log("Width: " + width + " Height: " + height);
ctx.clearRect(0, 0, width, height);
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
var index = findClosest(points, [x, y]);
var color = getColor(index);
<!-- console.log(color + " " + index); -->
ctx.fillStyle = color;
ctx.fillRect(x, y, 1, 1);
}
}
for (var i = 0; i < points.length; i++) {
ctx.fillStyle = 'white';
ctx.fillRect(points[i][0] - 1, points[i][1] - 1, 2, 2);
}
}
function init() {
points = [];
var numPoints = Math.min(($('screen').width * $('screen').height) / (300*300), 15);
console.log(numPoints);
for (var i = 0; i < numPoints; i++) {
points.push([Math.random() * $('screen').width, Math.random() * $('screen').height]);
console.log(points[i]);
}
}
function onclick(event) {
$('screen').width = window.innerWidth;
$('screen').height = window.innerHeight;
init();
step();
}
window.onload = function () {
setTimeout(onclick, 50);
setTimeout(function() {$('screen').observe('click', onclick);}, 1000);
//onclick();
//init();
//step();
};
</script>
</head>
<body style='margin: 0;'>
<canvas id="screen" width="100%" height="100%">
<p> you have no canvas </p>
</canvas>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment