123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- console.log('hi voronoi');
- const canvas = document.getElementById('canvas'),
- canvwidth = canvas.width,
- canvheight = canvas.height,
- ctx = canvas.getContext('2d');
- const minDist = 20,
- edgeBounds = 20;
- function drawSite(x, y) {
- ctx.save();
- ctx.beginPath();
- ctx.arc(x, y, 2, 0, Math.PI * 2, false);
- ctx.closePath();
- ctx.fillStyle = 'black';
- ctx.fill();
- ctx.restore();
- }
- function drawLine(x1, y1, x2, y2) {
- ctx.save();
- ctx.beginPath();
- ctx.strokeStyle = 'black';
- ctx.lineWidth = 1;
- ctx.moveTo(x1, y1);
- ctx.lineTo(x2, y2);
- ctx.stroke();
- ctx.restore();
- }
- function drawLineO(p1, p2) {
- drawLine(p1.x, p1.y, p2.x, p2.y);
- }
- function distance(p1, p2) {
- return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
- }
- function generateSites(n = 10) {
- const sites = [],
- safety = n * 2,
- randMultWidth = canvwidth - (edgeBounds * 2),
- randMultHeight = canvheight - (edgeBounds * 2),
- origin = {x:0, y:0};
- let count = 0;
- while( sites.length < n && count < safety ) {
- count += 1;
- const x = Math.floor(Math.random() * randMultWidth) + edgeBounds,
- y = Math.floor(Math.random() * randMultHeight) + edgeBounds,
- min = sites.reduce(function checkDist(minSoFar, existing) {
- const d = distance(existing, {x, y});
- if( d < minSoFar ) {
- return d;
- }
- else {
- return minSoFar;
- }
- }, canvwidth * canvheight);
- if( min > minDist ) {
- sites.push( {x, y} );
- }
- }
- sites.sort(function (a, b) {
- return distance(origin, a) - distance(origin, b);
- });
- return sites;
- }
- const sites = generateSites(15);
- sites.forEach(function renderSites(site) {
- drawSite(site.x, site.y);
- });
|