Last active
September 21, 2024 11:42
-
-
Save origedit/b8169d29fadda6bf26cdf0cb523819d0 to your computer and use it in GitHub Desktop.
voronoi diagram in p5.js
This file contains hidden or 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
let spread=50 | |
let dots={} | |
const palette=[ | |
"#583725", | |
"#b4785e", | |
"#f06128", | |
"#f8d81d", | |
"#e6ff8a", | |
"#92d425", | |
"#288554", | |
"#2aead9", | |
"#348db6", | |
"#d0e8f5", | |
"#1f2eae", | |
"#b783cd", | |
"#af2e7b", | |
"#ff95a2" | |
] | |
function setup() { | |
createCanvas(400, 400); | |
dotsX=width/spread; | |
dotsY=height/spread; | |
// setup dots | |
for(let y=0; y<dotsY; ++y){ | |
dots[y]={} | |
for(let x=0; x<dotsX; ++x){ | |
let col; | |
const look=[ | |
[-1, -1], | |
[0, -1], | |
[1, -1], | |
[-1, 0] | |
]; | |
do{ | |
col=palette[Math.floor(Math.random()*palette.length)]; | |
for(const lk of look){ | |
if(dots?.[y+lk[1]]?.[x+lk[0]]?.col==col){ | |
col=null; | |
break; | |
} | |
} | |
}while(!col); | |
function offset(x){ | |
const o=0.4 | |
return (x+random(0.5-o, 0.5+o))*spread; | |
} | |
dots[y][x]={ | |
"x": offset(x), | |
"y": offset(y), | |
"col": col | |
} | |
} | |
} | |
strokeWeight(1); | |
function dist2(x1, y1, x2, y2){ | |
return (x2-x1)**2 + (y2-y1)**2; | |
} | |
for(let sy=0; sy<dotsY; ++sy){ | |
for(let sx=0; sx<dotsX; ++sx){ | |
// pixels in each tile | |
const endY=(sy+1)*spread; | |
for(let y=sy*spread; y<endY; ++y){ | |
const endX=(sx+1)*spread; | |
for(let x=sx*spread; x<endX; ++x){ | |
// find the closest dot | |
let myDot = null; | |
let close = null; | |
for(const dy of [-1, 0, 1]){ | |
for(const dx of [-1, 0, 1]){ | |
let lookDot = dots?.[sy+dy]?.[sx+dx]; | |
if(!lookDot) continue; | |
let d = dist2(x, y, lookDot.x, lookDot.y); | |
if((close==null) || d<close){ | |
myDot = lookDot; | |
close = d; | |
} | |
} | |
} | |
stroke(myDot.col); | |
point(x+0.5, y+0.5); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment