voronoi
HTML
<body><canvas id="myCanvas" width="640" height="480" style="border:1px solid #000000;"/></body>
JavaScript
var can = document.getElementById("myCanvas");
var ctx = can.getContext("2d");
//make grid for calculating images. grid cointains index of the points in sources
//index = 0 if black, index = n if n-th color of nth sourcepoint
var width = 640;
var height = 480;
var grid = (new Array(height)).fill(0);
grid = grid.map(function(d){return (new Array(width)).fill(0);});
var gridbuffer = grid.map(function(d){return d.slice(0);}); //clone array
//generate some random initial points
var colours = ['#000000'];
var nsources = 30;
var sources = [];
for(var i=1;i<=nsources;i++){
var x = (Math.random()*width)|0;
var y = (Math.random()*height)|0;
sources.push({x:x,y:y});
grid[y][x] = i;
colours[i] = "#"+Math.random().toString(16).slice(2,8);
}
function writeGridToCanvas(){ //write the content of the grid to the canvas
console.log("writeGridToCanvas started");
for(var y = 0; y<height; y++){
for(var x = 0; x<width; x++){
//if(grid[y][x] == 0){alert(x+" , "+y);}
ctx.fillStyle = colours[grid[y][x]];
ctx.fillRect( x, y, 1, 1 );
}
}
for(var i=0;i<sources.length;i++){
ctx.beginPath();
ctx.fillStyle = '#000000';
ctx.arc(sources[i].x,sources[i].y,5,0,6.3);
ctx.stroke();
}
console.log("writeGridToCanvas done");
}
step();
function step(){//write voronoi cells
function getClosestSourceIndex(x,y){
var mindist = 1e10;
var minindex = 0;
var dist= new Array(sources.length);
var dx,dy;
for(var i=0;i< sources.length;i++){
dx = sources[i].x-x; dy = sources[i].y-y;
dist[i] = dx*dx+ dy*dy;
if(mindist>dist[i]){
mindist = dist[i];
minindex = i+1;
}
}
if(minindex==0){alert(x+","+y);}
return minindex;
}
/*function accessGrid(y,x){
try{
return grid[y][x];
} catch(e) {}
return 0;
}*/
//loop over each pixel and determine its nearest neighbour source
for(var x=0;x<width;x++){
for(var y=0;y<height;y++){
if(grid[y][x]==0){
gridbuffer[y][x] = getClosestSourceIndex(x,y);
} else {
gridbuffer[y][x] =...