Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              body {
  height: 100vh;
  background: url(https://res.cloudinary.com/marcofugaro/image/upload/v1570113726/simone-hutsch-skyscrapers_n7vgyi.jpg);
  background-size: cover;
  background-position: center center;
}

canvas {
  display: block;
}

            
          
!
            
              const simplex = new SimplexNoise()

const SLICES = 20
window.DEBUG = true

const stats = new Stats()
if (window.DEBUG) {
  document.body.appendChild(stats.dom)
}

class VoronoiSlices {
  image
  canvas = document.querySelector('canvas')
  ctx = this.canvas.getContext('2d')
  tStart = performance.now()
  voronoi
  points
  state

  constructor(image) {
    this.image = image

    const startingPoints = Array(SLICES)
      .fill(0)
      .map(() => [Math.random(), Math.random()])

    this.voronoi = d3.Delaunay.from(startingPoints).voronoi([0, 0, 1, 1])
    this.points = this.voronoi.delaunay.points

    this.state = ControlsState({
      relaxation: ControlsState.Slider(0.1, { min: 0, max: 1, step: 0.01 }),
      showCells: false,
      showCenters: false,
      noise: {
        enabled: true,
        amplitude: ControlsState.Slider(0.05, { min: 0, max: 0.5, step: 0.01 }),
        frequency: ControlsState.Slider(0.1, { min: 0, max: 10, step: 0.01 }),
      },
    })

    if (window.DEBUG) {
      this.state = ControlsGUI(this.state)
    }

    this.resize()
    window.addEventListener('resize', this.resize)

    requestAnimationFrame(this.update)
  }

  resize = () => {
    this.canvas.width = window.innerWidth
    this.canvas.height = window.innerHeight
  }

  xScale = (n) => {
    return n * this.canvas.width
  }

  yScale = (n) => {
    return n * this.canvas.height
  }

  scalePoint = (point) => {
    return [this.xScale(point[0]), this.yScale(point[1])]
  }

  scalePolygon = (polygon) => {
    return polygon.map(this.scalePoint)
  }

  drawPoint = (point, color) => {
    const RADIUS = 2.5

    this.ctx.beginPath()
    this.ctx.moveTo(point[0] + RADIUS, point[1])
    this.ctx.arc(point[0], point[1], RADIUS, 0, 2 * Math.PI, false)
    this.ctx.closePath()
    this.ctx.fillStyle = color
    this.ctx.fill()
  }

  drawLine = (from, to, color) => {
    const STROKE_WIDTH = 1

    this.ctx.beginPath()
    this.ctx.moveTo(from[0], from[1])
    this.ctx.lineTo(to[0], to[1])
    this.ctx.closePath()
    this.ctx.strokeStyle = color
    this.ctx.lineWidth = STROKE_WIDTH
    this.ctx.stroke()
  }

  drawPolygon = (polygon, color) => {
    const STROKE_WIDTH = 1
    
    this.ctx.beginPath()
    this.ctx.moveTo(polygon[0][0], polygon[0][1])
    for (let i = 1; i < polygon.length; i++) {
      const point = polygon[i]
      this.ctx.lineTo(point[0], point[1])
    }
    this.ctx.closePath()
    this.ctx.strokeStyle = color
    this.ctx.lineWidth = STROKE_WIDTH
    this.ctx.stroke()
  }

  drawImageClipped = (image, polygon, offset) => {
    this.ctx.save()
    this.ctx.beginPath()
    this.ctx.moveTo(polygon[0][0], polygon[0][1])
    for (let i = 1; i < polygon.length; i++) {
      const point = polygon[i]
      this.ctx.lineTo(point[0], point[1])
    }
    this.ctx.closePath()
    this.ctx.clip()

    const imageCoverSize = getCoverSize(
      image.naturalWidth,
      image.naturalHeight,
      this.canvas.width,
      this.canvas.height,
      0.5,
      0.5
    )

    this.ctx.drawImage(
      image,
      imageCoverSize.offsetLeft + offset[0],
      imageCoverSize.offsetTop + offset[1],
      imageCoverSize.width,
      imageCoverSize.height
    )

    this.ctx.restore()
  }

  update = (ms) => {
    const t = (ms - this.tStart) / 1000
    stats.begin()

    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)

    const polygons = Array.from(this.voronoi.cellPolygons())
    const centroids = polygons.map(d3.polygonCentroid)

    const EASING_FACTOR = this.state.relaxation
    const NOISE_AMPLITUDE = this.state.noise.amplitude
    const NOISE_FREQUENCY = this.state.noise.frequency
    for (let i = 0; i < this.points.length; i += 2) {
      // this is done also with bitwise operation i >> 1, but why the fuck
      const normalizedIndex = Math.floor(i / 2)

      const point = [this.points[i], this.points[i + 1]]
      const polygon = polygons[normalizedIndex]
      const centroid = centroids[normalizedIndex]

      if (!centroid) continue

      // apply LLoys's relaxation
      // https://observablehq.com/@mbostock/lloyds-algorithm
      // https://observablehq.com/@fil/spherical-lloyds-relaxation
      const target = _.cloneDeep(centroid)

      // give 'em a wobble
      if (this.state.noise.enabled) {
        target[0] += simplex.noise2D(i, t * NOISE_FREQUENCY) * NOISE_AMPLITUDE
        target[1] += simplex.noise2D(i + 1000, t * NOISE_FREQUENCY) * NOISE_AMPLITUDE
      }

      // ease the point to the target
      // https://aerotwist.com/tutorials/protip-stick-vs-ease/
      const x0 = point[0]
      const y0 = point[1]
      const [x1, y1] = target
      this.points[i] = x0 + (x1 - x0) * EASING_FACTOR
      this.points[i + 1] = y0 + (y1 - y0) * EASING_FACTOR

      const distance = [target[0] - this.points[i], target[1] - this.points[i + 1]]

      // draw!
      if (polygon) {
        this.drawImageClipped(image, this.scalePolygon(polygon), this.scalePoint(distance))
        if (this.state.showCells) {
          this.ctx.globalAlpha = 0.5
          this.drawPolygon(this.scalePolygon(polygon), '#000')
          this.ctx.globalAlpha = 1
        }
      }

      if (window.DEBUG && this.state.showCenters) {
        this.drawPoint(this.scalePoint(point), '#000')
        this.drawLine(this.scalePoint(point), this.scalePoint(target), '#000')
        this.drawPoint(this.scalePoint(target), '#f00')
      }
    }

    this.voronoi.update()

    stats.end()
    requestAnimationFrame(this.update)
  }
}

const image = new Image()
image.addEventListener('load', () => new VoronoiSlices(image))
image.src = 'https://res.cloudinary.com/marcofugaro/image/upload/v1570113726/simone-hutsch-skyscrapers_n7vgyi.jpg'

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console