voronoi.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. console.log('hi voronoi');
  2. const canvas = document.getElementById('canvas'),
  3. canvwidth = canvas.width,
  4. canvheight = canvas.height,
  5. ctx = canvas.getContext('2d');
  6. const minDist = 20,
  7. edgeBounds = 20;
  8. function drawSite(x, y) {
  9. ctx.save();
  10. ctx.beginPath();
  11. ctx.arc(x, y, 2, 0, Math.PI * 2, false);
  12. ctx.closePath();
  13. ctx.fillStyle = 'black';
  14. ctx.fill();
  15. ctx.restore();
  16. }
  17. function drawLine(x1, y1, x2, y2) {
  18. ctx.save();
  19. ctx.beginPath();
  20. ctx.strokeStyle = 'black';
  21. ctx.lineWidth = 1;
  22. ctx.moveTo(x1, y1);
  23. ctx.lineTo(x2, y2);
  24. ctx.stroke();
  25. ctx.restore();
  26. }
  27. function drawLineO(p1, p2) {
  28. drawLine(p1.x, p1.y, p2.x, p2.y);
  29. }
  30. function distance(p1, p2) {
  31. return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
  32. }
  33. function generateSites(n = 10) {
  34. const sites = [],
  35. safety = n * 2,
  36. randMultWidth = canvwidth - (edgeBounds * 2),
  37. randMultHeight = canvheight - (edgeBounds * 2),
  38. origin = {x:0, y:0};
  39. let count = 0;
  40. while( sites.length < n && count < safety ) {
  41. count += 1;
  42. const x = Math.floor(Math.random() * randMultWidth) + edgeBounds,
  43. y = Math.floor(Math.random() * randMultHeight) + edgeBounds,
  44. min = sites.reduce(function checkDist(minSoFar, existing) {
  45. const d = distance(existing, {x, y});
  46. if( d < minSoFar ) {
  47. return d;
  48. }
  49. else {
  50. return minSoFar;
  51. }
  52. }, canvwidth * canvheight);
  53. if( min > minDist ) {
  54. sites.push( {x, y} );
  55. }
  56. }
  57. sites.sort(function (a, b) {
  58. return distance(origin, a) - distance(origin, b);
  59. });
  60. return sites;
  61. }
  62. const sites = generateSites(15);
  63. sites.forEach(function renderSites(site) {
  64. drawSite(site.x, site.y);
  65. });