Exploring Voronoi Diagrams with p5.js

This weekend I dug into Voronoi diagrams.  Using the p5.voronoi library of Francisco Moreira, I created javascript which let me create my own set of points from math functions and then further manipulate the layouts.  I’ve shared some of the image results below, but you can try out the code yourself here.

  • Moving mouse changes the designs (interval and frequency)
  • Backspace toggles the fill on and off
  • Shift toggles the bezier curves on and off
  • 1 = sin + tan function
  • 2 = sin function only
  • Mouse-click toggles pause
  • S = screenshot

I used the following code to add bezier curves for all of the adjacent cell edges.

				
					if (bez) {
		//Draw with bezier curves
		strokeWeight(1);
		if (fillit) {
			stroke([0,0,100,100]);
		} else {
			stroke([204,100,95,100]);
		}
		noFill();
		var celllist = voronoiGetCells();
		for (let index = 0; index < celllist.length; index++) {
			for (let segment = 0; segment < celllist[index].length; segment++) {
				bezier(celllist[index][segment][0], celllist[index][segment][1], celllist[index][(segment+1) % celllist[index].length][0], +
				celllist[index][(segment+1) % celllist[index].length][1], celllist[index][(segment+1) % celllist[index].length][0], +
				celllist[index][(segment+1) % celllist[index].length][1], celllist[index][(segment+2) % celllist[index].length][0], +
				celllist[index][(segment+2) % celllist[index].length][1]);
			}
			
		}
	}
				
			

And this code creates the sites used to drive the voronoi diagram creation.

				
					function createSites(sites, inc, freq, type) {
	//Use this section to populate the sites array
	let amplitude = height/2;

	if (z > width) {
		z = 0;
	}
  	z+= 1;
  	for (x = 0; x < width; x+= inc) {
    	if (type == 1) {
			y = int((sin(radians(x*freq+z))+tan(radians(x*freq+z)))*amplitude+height/2);
		} else {
			y = int((sin(radians(x*freq+z))*amplitude+height/2));
		}
    	sites.push([x,y,[199,100,map(x % 32,0,32,0,100),100]]);
	}
	return sites;
}
				
			

Share This Post

Share on facebook
Share on twitter
Share on linkedin
Share on email

2 thoughts on “Exploring Voronoi Diagrams with p5.js”

  1. Hi Chris,
    Great website!

    My apologies for the n00b question. How do I include the p5.voronoi library in the code so p5js doesn’t need to pull the library?

    Thank you!
    -Mark

Leave a Comment

Your email address will not be published. Required fields are marked *

More To Explore