xxxxxxxxxx
56
function setup() {
randomSeed()
createCanvas(400, 400);
background("#747474");
const diameter = 3;
// Create candidates
const candidates = [];
for (let i = 0; i < 25; i++) {
candidates.push([
random(diameter, width - diameter),
random(diameter, height - diameter),
]);
}
// Color every pixel
const colors = ["#F44336", "#2196F3", "#4CAF50", "#FFEB3B", "#FF9800", "#00BCD4", "rgb(235,86,112)", "#673AB7"]
for (let y = 0; y < height; y += 1) {
for (let x = 0; x < width; x += 1) {
id = findNearestCandidate(x, y, candidates)
stroke(colors[id%colors.length]);
point(x + 5, y + 5);
}
}
// Draw candidates
for (let i = 0; i < candidates.length; i++) {
const x = candidates[i][0];
const y = candidates[i][1];
noStroke();
fill("#1A1A1A");
circle(x, y, diameter);
}
}
// Returns the nearest candidate id to the point (x,y)
function findNearestCandidate(x, y, candidates) {
let nearestDistance = 10000000
let nearestId = 0
for (let i = 0; i < candidates.length; i++) {
cx = candidates[i][0]
cy = candidates[i][1]
let distance = (x-cx)*(x-cx) + (y-cy)*(y-cy)
if (distance<nearestDistance){
nearestDistance = distance
nearestId = i
}
}
return nearestId
}