Fork me on GitHub

Javascript implementation of Steven Fortune's algorithm to compute Voronoi diagrams
Demo 1: measuring peformance

< Back to main page | Demo 1: measuring peformance | Demo 2: a bit of interactivity | Demo 3: Fancy tiling | Comments

Sites generator

or sites randomly (Warning: performance might suffer the more sites you add.)

Canvas

Javascript source code for this page

<script type="text/javascript" src="rhill-voronoi-core.js"></script>

...

<script type="text/javascript">
<!--
var VoronoiDemo = {

	voronoi: new Voronoi(),
	sites: [],
	diagram: null,
	margin: 50,
	canvas: null,
	bbox: {xl:0,xr:800,yt:0,yb:600},

	init: function() {
		this.canvas = document.getElementById('voronoiCanvas');
		this.randomSites(100,true);
		this.render();
		},

	clearSites: function() {
		this.sites = [];
		this.diagram = this.voronoi.compute(this.sites, this.bbox);
		this.updateStats();
		},

	randomSites: function(n,clear) {
		if (clear) {this.sites = [];}
		// create vertices
		var xo = this.margin;
		var dx = this.canvas.width-this.margin*2;
		var yo = this.margin;
		var dy = this.canvas.height-this.margin*2;
		for (var i=0; i<n; i++) {
			this.sites.push({x:self.Math.round((xo+self.Math.random()*dx)*10)/10,y:self.Math.round((yo+self.Math.random()*dy)*10)/10});
			}
		this.diagram = this.voronoi.compute(this.sites, this.bbox);
		this.updateStats();
		},

	updateStats: function() {
		if (!this.diagram) {return;}
		var e = document.getElementById('voronoiStats');
		if (!e) {return;}
		e.innerHTML = '('+this.diagram.cells.length+' Voronoi cells computed from '+this.sites.length+' Voronoi sites in '+this.diagram.execTime+' ms &ndash; rendering <i>not</i> included)';
		},

	render: function() {
		var ctx = this.canvas.getContext('2d');
		// background
		ctx.globalAlpha = 1;
		ctx.beginPath();
		ctx.rect(0,0,this.canvas.width,this.canvas.height);
		ctx.fillStyle = 'white';
		ctx.fill();
		ctx.strokeStyle = '#888';
		ctx.stroke();
		// voronoi
		if (!this.diagram) {return;}
		// edges
		ctx.beginPath();
		ctx.strokeStyle='#000';
		var edges = this.diagram.edges,
			iEdge = edges.length,
			edge, v;
		while (iEdge--) {
			edge = edges[iEdge];
			v = edge.va;
			ctx.moveTo(v.x,v.y);
			v = edge.vb;
			ctx.lineTo(v.x,v.y);
			}
		ctx.stroke();
		// sites
		ctx.beginPath();
		ctx.fillStyle = '#44f';
		var sites = this.sites,
			iSite = sites.length;
		while (iSite--) {
			v = sites[iSite];
			ctx.rect(v.x-2/3,v.y-2/3,2,2);
			}
		ctx.fill();
		},
	};
// -->
</script>
...