Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                canvas#canvas(height='100', width='100')
h1.text Voronoi
//- button.cascade Cascade
              
            
!

CSS

              
                html {
  font-family: 'Raleway', sans-serif;
}

body {
  background: linear-gradient(to bottom, #69859b 0%,#505d6b 100%);
  overflow:hidden;
}

#canvas {
  height: 100vh;
  width: 100vw;
  cursor: pointer;
  transition: all .5s ease-in-out;
  
  &:hover {
    box-shadow: 0 0 15px rgba(#eee,0.75);
  }
}

.text {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 20%;
  
  text-align: center;
  color: #eee;
  font-size: 30pt;
  letter-spacing: .15em;
  font-weight: 500;
  text-shadow: 0 0 5px black;
  z-index: 1;
  cursor: pointer;
}
              
            
!

JS

              
                const opts = {
  relaxations: 1, //num of lloyd relaxation iterations
  maxCells: 900, //max diagram cell count
  minCells: 300, // min
  hueMin: 0,
  hueMax: 360,
  hueDistMin: 10,
  hueDistMax: 100
};

/** TODO
* Better pass-through than argument->argument for hueStart/hueDist
* Use ES6
*/


/**
 *
 * generate and return voronoi diagram
 *
 */
function newVoronoi() {
  var numCells = Math.round(rand(opts.minCells, opts.maxCells)),
    voronoi = new Voronoi(),
    bbox = {
      xl: 0,
      xr: w,
      yt: 0,
      yb: h
    },
    sites = (function() {
      var s = [];
      for (var i = 0; i < numCells; i++) {
        s.push({
          x: Math.random() * w,
          y: Math.random() * h
        });
      }
      return s;
    })(),
    diagram = voronoi.compute(sites, bbox);

  // apply lloyd relaxition to centroid for equally sized cells
  // centroid appoximated by averaging endpoints of cell edges
  for (var r = 0; r < opts.relaxations; r++) {
    sites = [];
    diagram.cells.forEach(function(c) {
      var len = c.halfedges.length,
        av_x = 0,
        av_y = 0;

      c.halfedges.forEach(function(edge) {
        av_x += edge.getEndpoint().x;
        av_y += edge.getEndpoint().y;
      });

      sites.push({
        x: av_x / len,
        y: av_y / len
      });
    });

    diagram = voronoi.compute(sites, bbox);
  }

  return diagram;
}


/* Draw all cells in a diagram */
function drawVoronoi(diagram) {
  // Draw computed cells
  let cellCounter = 0,
      hueDist= rand(opts.hueDistMin, opts.hueDistMax),
      hueStart = rand(opts.hueMin, opts.hueMax - hueDist);
  
  console.log('--draw');
  console.log('hueDist:  ' + hueDist);
  console.log('hueStart: ' + hueStart);
  
  for (let i = 0; i < diagram.cells.length; i++) {
    drawCell(diagram.cells[cellCounter++], hueStart, hueDist);
  }
}


/* Draw a single cell */
function drawCell(cell, hueStart, hueDist) {
  var edge,
    start = cell.halfedges[0].edge,
    end = cell.halfedges[cell.halfedges.length - 1].edge,
    cx = cell.site.x,
    cy = cell.site.y,
    color = getHslColor(cx, cy, hueStart, hueDist),
    border = darkenHsl(color, 0.35),
    path = new paper.Path();

  var s, e;
  // path.strokeColor = border.string;
  path.fillColor = path.strokeColor = color.string;
  path.add(new paper.Point(start.va.x, start.va.y));

  for (var j = 0; j < cell.halfedges.length; j++) {
    edge = cell.halfedges[j];
    s = edge.getStartpoint();
    e = edge.getEndpoint();
    path.add(new paper.Point(s.x, s.y));
    path.add(new paper.Point(e.x, e.y));
  }

  path.closed = true;
}



/**
 *
 * HELPERS
 *
 */
/* Random number */
function rand(min, max) {
  return min + Math.random() * (max - min);
}

function lerp(t, a, b) {
  return a + t * (b - a);
}

function ilerp(c, a, b) {
  return (c - a) / (b - a);
}

/* Cell coloring */
function getHslColor(x, y, hueStart, hueDist) {
  var r = rand(0, 1) - .5,
    h0 = hueStart || 130;

  var perx = ilerp(x, 0, w),
    pery = ilerp(y, 0, h),
    _h = (hueStart + hueDist * (perx + r / 4) + (hueDist + rand(-10,20)) * (pery - r / 4)) % 360,
    _s = 45 + 15.0 * r + rand(-5,5),
    _l = 50 + 15.0 * (pery + perx + r / 2) / 2 + rand(-10,10);

  return {
    hsl: [_h, _s, _l],
    string: 'hsl(' + _h + ',' + _s + '%,' + _l + '%)'
  };
}

/* Darken HSL color object */
function darkenHsl(oldc, perc) {
  var newc = {
    hsl: oldc.hsl.slice(0),
    string: ''
  };

  newc.hsl[2] *= (1 - perc);
  newc.string = 'hsl(' + newc.hsl[0] +
    ',' + newc.hsl[1] + '%' +
    ',' + newc.hsl[2] + '%' + ')';
  return newc;
}


/**
 *
 * MAIN
 *
 */
var canvas = document.getElementById('canvas'),
  h = canvas.height,
  w = canvas.width,
  ctx = canvas.getContext('2d'),
  vordia;

// using paperjs
paper.setup(canvas);

/* Size canvas and draw new voronoi diagram */
function drawOnCanvas() {
  w = canvas.width = window.innerWidth;
  h = canvas.height = window.innerHeight;
  if (vordia) paper.project.activeLayer.removeChildren();
  vordia = newVoronoi();
  drawVoronoi(vordia);
}

/* paperjs needs to wait for doc ready */
window.onload = drawOnCanvas;

/* Event handlers */
window.addEventListener('resize', drawOnCanvas);
canvas.addEventListener('click', drawOnCanvas);
              
            
!
999px

Console