Pen Settings

HTML

CSS

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

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

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

Behavior

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.

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

              
                <section class="content" id="content" style="background-image: url(https://user-images.githubusercontent.com/22446806/41007083-d9fd9216-692c-11e8-9b12-4682bfd0ba63.jpeg)">

  <nav id="menu" class="menu" data-id="3">
    <canvas id="menu-bg" class="menu-bg"></canvas>
    <ul class="menu-list" id="menu-list">
      <li class="menu-item" style="--c: #6b006b;">
          <span class="slide-letter"><span>I</span></span>
          <span class="slide-letter"><span>m</span></span>
          <span class="slide-letter"><span>i</span></span>
          <span class="slide-letter"><span>t</span></span>
          <span class="slide-letter"><span>a</span></span>
          <span class="slide-letter"><span>t</span></span>
          <span class="slide-letter"><span>i</span></span>
          <span class="slide-letter"><span>o</span></span>
          <span class="slide-letter"><span>n</span></span>
      </li>
      <li class="menu-item" style="--c: #b9c503;">
        <span class="slide-letter"><span>D</span></span>
        <span class="slide-letter"><span>i</span></span>
        <span class="slide-letter"><span>s</span></span>
        <span class="slide-letter"><span>c</span></span>
        <span class="slide-letter"><span>o</span></span>
        <span class="slide-letter"><span>v</span></span>
        <span class="slide-letter"><span>e</span></span>
        <span class="slide-letter"><span>r</span></span>
        <span class="slide-letter"><span>y</span></span>
      </li>
      <li class="menu-item" style="--c: #104e90;">
        <span class="slide-letter"><span>C</span></span>
        <span class="slide-letter"><span>o</span></span>
        <span class="slide-letter"><span>m</span></span>
        <span class="slide-letter"><span>m</span></span>
        <span class="slide-letter"><span>i</span></span>
        <span class="slide-letter"><span>t</span></span>
        <span class="slide-letter"><span>m</span></span>
        <span class="slide-letter"> <span>e</span></span>
        <span class="slide-letter"><span>n</span></span>
        <span class="slide-letter"><span>t</span></span>
      </li>
      <li class="menu-item" style="--c: #800101;">
        <span class="slide-letter"><span>L</span></span>
        <span class="slide-letter"><span>e</span></span>
        <span class="slide-letter"><span>g</span></span>
        <span class="slide-letter"><span>a</span></span>
        <span class="slide-letter"><span>c</span></span>
        <span class="slide-letter"><span>y</span></span>
      </li>
    </ul>
  </nav>

  <button id="menu-toggle" class="menu-toggle">menu</button>

  <h1 class="heading heading--in" id="heading">
    <span class="slide-letter"><span>C</span></span>
    <span class="slide-letter"><span>o</span></span>
    <span class="slide-letter"><span>m</span></span>
    <span class="slide-letter"><span>m</span></span>
    <span class="slide-letter"><span>i</span></span>
    <span class="slide-letter"><span>t</span></span>
    <span class="slide-letter"><span>m</span></span>
    <span class="slide-letter"><span>e</span></span>
    <span class="slide-letter"><span>n</span></span>
    <span class="slide-letter"><span>t</span></span>
  </h1> 
</section>
              
            
!

CSS

              
                @font-face {
  font-family: 'Monoton';
  font-style: normal;
  font-weight: 400;
  src: local('Monoton'), local('Monoton-Regular'), url(https://fonts.gstatic.com/s/monoton/v7/5h1aiZUrOngCibe4TkHLQka4BU4.woff2) format('woff2');
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}

$menu-items: 4;
$max-letters: 10;
$letter-tr: 102%;
$clr-menu: #e0e0e0;
$clr-primary: #171717;

*, *::before, *::after {
  box-sizing: border-box;
}

body {
  margin: 0;
  min-height: 100vh;
}

.content {
  min-height: 100vh;
  display: flex;
  background-position: center;
  background-size: cover;
}

.menu-bg {
  position: absolute;
  transition: background-color 1s;

  .menu--open &, .menu--transition & {
    background-color: hsla(0, 100%, 0%, .65);
  }
}

.menu {
  display: none;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 2;
}

.menu-list {
  margin: 0;
  padding: 0;
  list-style: none;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  align-items: center;
  width: 100%;
  height: 100%;
  user-select: none;
}

$line-tr: -101%;

.menu-item {
  position: relative;
  margin: 0;
  text-transform: uppercase;
  color: $clr-menu;
  text-align: center;
  font-size: 0;
  font-family: 'Monoton', cursive;
  line-height: 1.2;
  overflow: hidden;
  padding: 0 5%;
  pointer-events: none;

  .menu--open & {
    pointer-events: all;
  }

  @media (hover: hover) {
    &::before {
      $h: 40%;

      content: '';
      position: absolute;
      width: 100%;
      height: $h;
      left: 0;
      top: calc(50% - #{$h} / 2 - 2px);
      background-color: var(--c);
      transform: translateX($line-tr);
      will-change: transform;
      transition: transform .3s cubic-bezier(.2,.58,.61,.96);
      filter: invert(1);
      mix-blend-mode: difference;
      z-index: 1;
    }

    &:hover::before {
      transform: translateX(0);

      .menu--transition & {
        transition-duration: 1s;
        transform: translateX($line-tr);
      }

      .menu--reverse & {
        transform: translateX($line-tr);
      }
    }
  }
}

.menu--open .slide-letter span {
  transform: translateX(0);
}
.menu--transition .slide-letter span {
  transform: translateX(-$letter-tr);

  @media only screen and (max-aspect-ratio: 1/1) {
    transform: translateY(-$letter-tr);
  }
}

.slide-letter {
  overflow: hidden;

  &, span {
    display: inline-block;
    pointer-events: none;
  }

  span {
    transition: transform .3s ease-out;
    transform: translateX($letter-tr);
    font-size: calc(14px + 5vw);

    @media only screen and (max-aspect-ratio: 1/1) {
      transform: translateY($letter-tr);
    }
  }

  @for $i from 1 through $max-letters {
    &:nth-child(#{$i}) span {
      transition-delay: calc((0.05 * #{$i} + var(--slide-delay, 0)) * 1s);
    }
  }
}
 
@for $i from 1 through $menu-items {
  .menu-item:nth-child(#{$i}) {
    --slide-delay: calc(#{$i} * .1);
  }
}

 .menu-toggle {
  $bw: 3rem; $w: 60%; $h: 4px;

  margin: 3rem;
	position: absolute;
	overflow: hidden;
	z-index: 2;
	text-indent: 9999px;
	display: inline-block;
	width: $bw;
	height: $bw;
	border: none;
  transition: all .3s;
  background-color: transparent;

  &:focus {
    // Don't do this at home
    outline: none;
  }

  &--hidden {
    opacity: 0;
    pointer-events: none;
  }

  &::before,
  &::after {
    content: '';
    width: $w;
    height: $h;
    background-color: var(--color, $clr-primary);
    position: absolute;
    transition: transform .3s;
    will-change: transform;
    border-radius: 1px;
  }

  $ofst: (100% - $w) / 2;
  $o-ofst: calc(50% - #{$h} / 2);
  $scale: .5;

  &::before {
    top: $bw / 3;
    left: $ofst;
    transform-origin: 100% 50%;
    transform: scaleX(1.3);
  }

  &::after {
    bottom: $bw / 3;
    right: $ofst;
    transform-origin: 0 50%;
    transform: scaleX(1.3);
  }

  &:not(.menu-toggle--opened):hover::before,
  &:not(.menu-toggle--opened):hover::after {
    transform: scaleX(1)
  }

  &--opened {
    --color: #{$clr-menu};

    transform: rotate(45deg);

    &:hover {
      transform: rotate(60deg);
    }

    &::before {
      height: 100%;
      width: $h;
      top: 0;
      left: $o-ofst;
    }

    &::after {
      width: 100%;
      right: 0;
      top: $o-ofst;
    }

    &::before, &::after {
      transform-origin: 50%;
      transform: scale(1);
    }

    &:hover::before {
      transform: scaleY($scale);
    }

    &:hover::after {
      transform: scaleX($scale);
    }
  }
}

.heading {
  margin: auto;
  font-size: 0;
  align-self: center;
  transition: opacity .3s;
  user-select: none;
  font-family: "Arial Black", "Arial Bold", Gadget, sans-serif;
  text-transform: uppercase;
  color: $clr-primary;
  user-select: none;

  .slide-letter {
    margin-left: -1px;
  }

  .slide-letter span {
    font-size: calc(16px + 7vw);
    transition-property: none;
    text-decoration: underline;
  }

  &--out .slide-letter span {
    transform: translateX(-$letter-tr);
    transition-property: transform;
  }

  &--in .slide-letter span {
    transform: translateX(0);
    transition-property: transform;
  }
}

              
            
!

JS

              
                // Lasciate ogni speranza, voi ch'entrate

const noop = () => {}
const linear = n => n
 
class Block {
  constructor ({
    transitionEasing,
    moveEasing,
    
    onBlockTransitionFinish = noop,
    
    ...rest
  }) {
    Object.assign(this, {
      moveDelay: 0,
      x: rest.initialX,
      y: rest.initialY,
      initialBg: rest.bg,
      moveStart: performance.now(),
      transitColorCache: new Map(),
      finalColorCache: new Map(),

      reverseTransition: false,
      moveFinished: false,
      transition: false,
      shouldColor: false,
      shouldScale: false,

      props: {
        transitionEasing,
        moveEasing,
        onBlockTransitionFinish,
      }
    }, rest)
  }

  move (time) {
    time -= this.moveStart

    if (time < this.moveDelay) return

    const progress = this.props.moveEasing((time - this.moveDelay) / this.moveDur)

    if (progress > 1) {
      if (!this.moveFinished) {
        this.moveFinished = true
        this.x = this.finalX
        this.y = this.finalY
      }

      return
    }

    this.x = lerp(this.initialX, this.finalX, progress)
    this.y = lerp(this.initialY, this.finalY, progress)
  }

  moveBackwards () {
    const tempX = this.finalX
    const tempY = this.finalY

    this.finalX = this.initialX
    this.finalY = this.initialY
    this.initialX = tempX
    this.initialY = tempY

    this.moveStart = performance.now()

    if (this.moveFinished) this.moveFinished = false
  }

  update (now) {
    this.move(now)

    if (this.transition) {
      this.updateTransitionProgress(now)

      this.shouldColor && this.color()
      this.shouldScale && this.scale()
    }

    // for chaining
    return this
  }

  updateTransitionProgress (time) {
    time -= this.transitionStart

    const progress = this.props.transitionEasing(
      Math.max(Math.min(time / this.transitionDur, 1), 0)
    )

    if (!this.reverseTransition) {
      this.prevTransitionProgress = this.transitionProgress = progress
    } else {
      this.transitionProgress = Math.max(this.prevTransitionProgress - progress, 0)

      if (this.transitionProgress <= 0) this.transitionFinish()
    }
  }

  color () {
    const p = this.transitionProgress

    if (p >= 1) return

    /*
    this.bg = (!this.shouldScale || !this.shouldColor)
      ? interpolateColor(this.initialBg, this.finalBg, p)
      : this.getColor(p)
    */
    this.bg = interpolateColor(this.initialBg, this.finalBg, p)
  }

  getColor (progress) {
    let cache = this.transitColorCache.get(this.finalColor)

    if (!cache) {
      cache = new Map()
      this.transitColorCache.set(this.finalColor, cache)
    }

    let bg = cache.get(progress.toFixed(2))

    if (!bg) {
      bg = interpolateColor(this.initialBg, this.finalBg, progress)

      cache.set(progress.toFixed(2), bg)
    }

    return bg
  }

  transitionPrepare (color, id, shouldScale = true) {
    this.transitionId = id
    this.transitionStart = performance.now()
    this.transition = this.shouldColor = true
    this.transitionDur = r(500, 1500)
    this.setFinalBg(color)
    this.shouldScale = shouldScale

    if (shouldScale)
      this.finalScale = 1 + Math.random() * 0.1
  }

  transitionBackwardsPrepare (shouldColor = true) {
    this.transitionStart = performance.now()
    this.reverseTransition = true
    this.shouldColor = shouldColor
  }

  transitionFinish () {
    this.bg = this.initialBg
    this.reverseTransition = this.transition =
      this.shouldScale = this.shouldColor = false

    this.props.onBlockTransitionFinish(this)
  }

  shouldTransitionBackwards (id) {
    return this.transitionId === id
  }

  setFinalBg(color) {
    this.setBg(color, 'final')
    this.finalColor = color
  }

  setInitialBg(color) {
    this.setBg(color, 'initial')
  }

  setBg (color, type) {
    let bg = this.finalColorCache.get(color)

    if (!bg) {
      bg = generateNoiseBg(
        this.size,
        this.size,
        this.colorTemplates[color],
        this.coeffs
      ).bg

      this.finalColorCache.set(color, bg)
    }

    this[`${type}Bg`] = bg
  }

  scale () {
    const { cx } = this
    const { width: w, height: h } = cx.canvas

    const scaleF = lerp(1, this.finalScale, this.transitionProgress)

    this.scaleF = scaleF

    cx.save()
    cx.translate(w / 2, h / 2)
    cx.scale(scaleF, scaleF)
    cx.translate(-w / 2, -h / 2)
  }

  draw () {
    const { cx } = this

    cx.globalAlpha = this.alpha
    cx.drawImage(this.bg, this.x, this.y)
    cx.restore()
  }
}

class FloatingBlock extends Block {
  move (time) {
    if (this.moveFinished) {
      if (!this.originSaved) this.saveOrigin()

      const { x, y } = interpolateCoords(
        { x: this.x, y: this.y },
        { x: this.finalX, y: this.finalY },
        0.05
      )

      this.x = x
      this.y = y

      return
    }

    super.move(time)
  }

  saveOrigin () {
    this.ox = this.x
    this.oy = this.y
    this.originSaved = true
  }

  float (xCoeff, yCoeff) {
    this.finalX = this.ox + (this.floatArea * xCoeff) * this.dir
    this.finalY = this.oy + (this.floatArea * yCoeff) * this.dir
  }

  moveFinal () {
    this.moveFinished = false
    this.initialX = this.x
    this.initialY = this.y
    this.finalX = this.finalXBuf
    this.finalY = this.finalYBuf
    this.moveStart = performance.now()
  }
}

class Menu {
  constructor ({
    transitionEasing = linear,
    moveEasing = linear,

    onMenuTransitionFinish = noop,
    onMenuOpen = noop,
    onMenuClose = noop,
    onMenuAssemble = noop,
    onMenuItemClick = noop,

    $menu,

    ...rest
  }) {
    const $canvas = $menu.querySelector('#menu-bg')

    this.landscape = innerWidth > innerHeight
    this.hoverDevice = matchMedia('(hover: hover)').matches
    this.cx = $canvas.getContext('2d')

    this.onMouseOver = this.onMouseOver.bind(this)
    this.onMouseOut = this.onMouseOut.bind(this)
    this.onMouseMove = this.onMouseMove.bind(this)
    this.onItemClick = this.onItemClick.bind(this)

    matchMedia('(min-aspect-ratio: 1/1)').addListener(({ matches }) => {
      this.landscape = matches
    })

    this.onBlockTransitionFinish = this.onBlockTransitionFinish.bind(this)

    this.transitionId = this.maxFloatingDur = this.mouseMoveTimer = 0

    this.$menu = $menu
    this.$canvas = $canvas

    this.scalingBlocksAmount = rest.scalingBlocksAmount
    this.blockSize = rest.blockSize

    this.colorTemplates = generateColorTemplates($menu.querySelector('#menu-list'))

    this.updateDimensions()  
    window.onresize = this.updateDimensions.bind(this) 

    // options that aren't used by Menu directly
    this.props = {
      transitionEasing,
      moveEasing
    }

    this.hooks = {
      onMenuTransitionFinish,
      onMenuOpen,
      onMenuClose,
      onMenuAssemble,
      onMenuItemClick
    } 

    this.createRenderer()
  }

  updateDimensions () {
    const [iw, ih] = [innerWidth, innerHeight]

    this.$canvas.width = iw
    this.$canvas.height = ih
    this.halfWidth = iw / 2
    this.halfHeight = ih / 2
  }

  onItemClick ({ target }) {
    const $menuItem = target.closest('.menu-item')

    if (!$menuItem) return

    const { $menu } = this
    const curId = [...$menuItem.parentNode.children]
      .findIndex($el => $el === $menuItem) + 1

    this.hooks.onMenuItemClick()

    if (+$menu.dataset.id === curId) {
      $menu.classList.add('menu--reverse')

      this.reverseTransitionBlocks()
      this.close()

      return
    }

    const color = $menuItem.style.getPropertyValue('--c').trim()

    $menu.classList.add('menu--transition')
    $menu.dataset.id = curId

    this.floatingBlocks.forEach(block => {
      block.moveFinal()
      block.transitionPrepare(color, null, false)
    })

    this.inPlaceBlocks.forEach(block => {
      if (block.transition) {
        block.setInitialBg(color)

        if (!block.reverseTransition)
          block.transitionBackwardsPrepare(false)
      }
      else block.transitionPrepare(color, null, false)
    })

    this.close(true, $menuItem)
  }

  onMouseMove ({ pageX: x, pageY: y }) {
    const { halfWidth: hw, halfHeight: hh } = this

    this.floatingBlocks.forEach(block => {
      const xCoeff = (x - hw) / hw
      const yCoeff = (hh - y) / hh

      block.float(xCoeff, yCoeff)
    })
  }

  onMouseOver ({ target }) {
    const $menuItem = target.closest('.menu-item')

    if (!$menuItem) return

    this.transitionId++

    const { inPlaceBlocks, transitionBlocks } = this
    const { length } = inPlaceBlocks
    const color = $menuItem.style.getPropertyValue('--c').trim()

    let amount = this.scalingBlocksAmount

    while (amount--) {
      let block

      do block = inPlaceBlocks[Math.floor(Math.random() * length)]
      while (~transitionBlocks.indexOf(block))

      transitionBlocks.push(block)

      block.transitionPrepare(color, this.transitionId)
    }
  }

  onMouseOut ({ target }) {
    target.closest('.menu-item') && this.reverseTransitionBlocks()
  }

  reverseTransitionBlocks () {
    this.transitionBlocks.forEach(block =>
      block.shouldTransitionBackwards(this.transitionId) &&
      block.transitionBackwardsPrepare()
    )
  }

  onBlockTransitionFinish (block) {
    const { transitionBlocks } = this
    transitionBlocks.splice(transitionBlocks.indexOf(block), 1)
  }

  attachListeners (dur) {
    if (this.hoverDevice) {
      this.$menu.addEventListener('mouseover', this.onMouseOver)
      this.$menu.addEventListener('mouseout', this.onMouseOut)
    }
    
    this.mouseMoveTimer = setTimeout(() => {
      document.addEventListener('mousemove', this.onMouseMove)
      this.$menu.addEventListener('click', this.onItemClick)
    }, dur)
  }

  detachListeners () {
    this.$menu.removeEventListener('click', this.onItemClick)

    if (this.hoverDevice) {
      this.$menu.removeEventListener('mouseover', this.onMouseOver)
      this.$menu.removeEventListener('mouseout', this.onMouseOut)
      document.removeEventListener('mousemove', this.onMouseMove)
    }
  }

  initializeBlocks () {
    const { $canvas, cx } = this
    const { width: cw, height: ch } = $canvas

    const getCommonOptions = (i, j, s) => {
      const { bg, coeffs } = generateNoiseBg(s, s, this.colorTemplates['#000'])

      // Opitons that depend on the device's width/height ratio
      const dimOpts = this.landscape
        ? {
          finalX: j * s,
          finalY: i * s,
          initialX: cw,
          initialY: ~~(Math.random() * ch)
        }
        : {
          finalX: i * s,
          finalY: j * s,
          initialX: ~~(Math.random() * cw),
          initialY: ch
        }

      return {
        size: s,
        alpha: 0.8 + Math.random() * 0.2,
        moveDur: r(500, 1000),
        initialBg: bg,
        moveDelay: r(100, 500),

        colorTemplates: this.colorTemplates,

        transitionEasing: this.props.transitionEasing,
        moveEasing: this.props.moveEasing,
        onBlockTransitionFinish: this.onBlockTransitionFinish,
        coeffs,
        cx,
        bg,

        ...dimOpts
      }
    }

    const inPlaceBlocks = [], floatingBlocks = []
    const s = ~~(Math.max(cw, ch) * (this.blockSize / 100))
    const [w, h] = [cw, ch].map(n => ~~(n / s))
    const maxGridDim = Math.max(w, h)
    const [min, max] = [0.4, 0.7].map(n => ~~(maxGridDim * n))
    const diffs = [1]
    
    let id = 1, maxTransitionTime = 0, row = ~~(maxGridDim / 2)

    /*
      Whether the assembled part of the background has

        cog-like appearance, e.g.

        OOOOOOOOO
        OOOOOOO
        OOOOOOOOO
        OOOOOOO
        OOOOOOOOO

        stairs-like appearance, e.g.

        OOOOOOOOO
        OOOOOOO
        OOOOO
    */
    const cogLike = diff =>
      diffs.length > 3 && diffs.slice(-3).reduce((p, n) => p + n) + diff === 0

    const stairsLike = (diff, n) =>
      diffs.length > n &&
      Math.abs(diffs.slice(-n).reduce((p, n) => p + n) + diff) === n + 1

    for (let i = 0; i <= Math.min(w, h); i++) {
      let j = 0

      do {
        inPlaceBlocks.push(
          new Block(getCommonOptions(i, j, s))
        )
      } while (++j <= row)

      let nextRowDiff = Math.random() < 0.5 ? 1 : -1

      if (cogLike(nextRowDiff) || stairsLike(nextRowDiff, 2))
        nextRowDiff *= -1

      diffs.push(nextRowDiff)

      row += nextRowDiff

      do {
        const opts = getCommonOptions(i, j, s)
        const d =  0.5 + Math.random() * 0.5
        const initialX = opts.initialX * 1.5


        Object.assign(opts, {
          floatArea: Math.random() * 50,
          dir: Math.random() > 0.5 ? 1 : -1,
          finalX: lerp(initialX, opts.finalX, d),
          finalY: lerp(opts.initialY, opts.finalY, d),
          finalXBuf: opts.finalX,
          finalYBuf: opts.finalY,
          moveDelay: opts.moveDelay * 1.5,
          id: id++,
          initialX
        })

        const totalTransitionTime = opts.moveDelay + opts.moveDur

        if (totalTransitionTime > maxTransitionTime)
          maxTransitionTime = totalTransitionTime

        floatingBlocks.push(new FloatingBlock(opts))
      } while (++j <= maxGridDim)
    }

    this.maxTransitionTime = maxTransitionTime
    this.inPlaceBlocks = inPlaceBlocks
    this.floatingBlocks = floatingBlocks
    this.transitionBlocks = []
  }

  createRenderer () {
    const render = (block, time) => block.update(time).draw()
    const { $canvas, cx } = this
    let rafId = 0

    const loop = time => {
      cx.clearRect(0, 0, $canvas.width, $canvas.height)

      this.inPlaceBlocks.forEach(block =>
        !block.shouldScale && render(block, time)
      )

      this.transitionBlocks.sort((p, n) => p.scaleF > n.scaleF ? 1 : -1)

      this.floatingBlocks
        .concat(this.transitionBlocks)
        .forEach(block => render(block, time))

      rafId = requestAnimationFrame(loop)
    }

    this.renderer = {
      stop () {
        cancelAnimationFrame(rafId)
      },
      run () {
        loop(performance.now())
      }
    }
  }

  toggle () {
    if (this.inTransit) return

    this.opened ? this.close() : this.open()
  }

  open () {
    this.hooks.onMenuOpen()
    this.initializeBlocks()

    this.opened = true

    this.$menu.style.display = 'block'
     setTimeout(() => this.$menu.classList.add('menu--open'), 0)

    this.attachListeners(this.maxTransitionTime)
    this.lockFor(this.maxTransitionTime).then(this.hooks.onMenuAssemble)
    this.renderer.run()
  }

  reverseBlocks () {
    this.inPlaceBlocks
      .concat(this.floatingBlocks)
      .forEach(b => b.moveBackwards())
  }

  close (isTransition = false, $clickedItem) {
    clearTimeout(this.mouseMoveTimer)

    this.detachListeners()

    if (!isTransition)
      this.reverseBlocks()

    this.opened = false

    const { $menu, maxTransitionTime } = this

    $menu.classList.remove('menu--open')

    const transitionFinishedPromise = new Promise(resolve => {
      setTimeout(async () => {
        this.renderer.stop()

        $menu.className = 'menu'

        if (isTransition)
          await this.hooks.onMenuTransitionFinish(this.$canvas, $clickedItem)

        $menu.style.display = 'none'

        resolve()
      }, maxTransitionTime)
    })

    this.lockFor(maxTransitionTime, transitionFinishedPromise)
      .then(this.hooks.onMenuClose)
  }

  lockFor (dur, promise = Promise.resolve()) {
    return new Promise(resolve => {
      this.inTransit = true

      setTimeout(async () => {
        await promise
        this.inTransit = false
        resolve()
      }, dur)
    })
  }
}

function splitColorIntoChannels (color) {
  // short hex -> full hex
  if (color.length === 3) {
    for (let i = 0; i < color.length; i += 2) {
      color.splice(i + 1, 0, color[i])
    }
  }

  const splittedColor = []

  for (let i = 0; i < color.length; i += 2)
    splittedColor.push(color.slice(i, i + 2).join(''))

  return splittedColor
}

function generateColorTemplates (
  $menuList,
  colorTemplates = {
    '#000': [{ min: 0, max: 0x12 }, { min: 0, max: 0x12 }, { min: 0, max: 0x12 }]
  }
) {
  const chDeviation = 32

  return [...$menuList.children].reduce((templates, $menuItem) => {
    const color = $menuItem.style.getPropertyValue('--c').trim()

    templates[color] = splitColorIntoChannels([...color.slice(1)])
      .map(ch => {
        ch = parseInt(ch, 16)

        return {
          min: Math.max(ch - chDeviation, 0),
          max: Math.min(ch + chDeviation, 255)
        }
      })

    return templates
  }, colorTemplates)
}

function r (min, max) {
  return ~~(Math.random() * (max - min) + min)
}

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

function interpolateCoords (a, b, i) {
  return {
    x: lerp(a.x, b.x, i),
    y: lerp(a.y, b.y, i)
  }
}

function interpolateColor ($from, $to, coeff) {
  const [
    { width, height, data: fromData, data: { length } }, 
    { data: toData }
  ] = [$from, $to].map($c =>
    $c.getContext('2d').getImageData(0, 0, $c.width, $c.height)
  )

  for (let i = 0; i < length; i += 4) {
    for (let j = i; j < i + 3; j++) {
      fromData[j] = lerp(fromData[j], toData[j], coeff)
    }
  }

  return putDataIntoCanvas(fromData, width, height)
}

function putDataIntoCanvas (data, width, height) {
  const $canvas = document.createElement('canvas')
  const ctx = $canvas.getContext('2d')

  $canvas.width = width
  $canvas.height = height
  ctx.putImageData(new ImageData(data, width, height), 0, 0)

  return $canvas
}

function generateNoiseBg (w, h, colorTemplate, coeffs = []) {
  const getCurrentColor = coeff => 
    colorTemplate.map(({ min, max }) => ~~lerp(min, max, coeff))

  const len = w * h * 4
  const imageData = new Uint8ClampedArray(len)

  if (coeffs.length) {
    for (let i = 0, j = 0; i < len; i += 4, j++) {
      putColorToImageData(getCurrentColor(coeffs[j]), i)
    }
  } else {
    for (let i = 0; i < len; i += 4) {
      const coeff = Math.random()

      putColorToImageData(getCurrentColor(coeff), i)

      coeffs.push(coeff)
    }
  }

  return {
    bg: putDataIntoCanvas(imageData, w, h),
    coeffs
  }

  function putColorToImageData (color, i) {
    imageData[i] =  color[0]
    imageData[i + 1] =  color[1]
    imageData[i + 2] =  color[2]
    imageData[i + 3] =  255
  } 
}
  
function circInOut (m) {
  return ((m /= 0.5) < 1)
    ? (-0.5 * (Math.sqrt(1 - m * m) - 1))
    : (0.5 * (Math.sqrt(1 - (m -= 2) * m) + 1))
}

function power3Out (m) {
  return (--m) * m * m + 1
} 

async function blendImages ($elem, $canvas) {  
  const canvasBg = getComputedStyle($canvas).backgroundColor
  const { backgroundImage: bgi, backgroundColor: bgc } = getComputedStyle($elem) 
  const elemBg = bgi === 'none' ? bgc : bgi
  const [iw, ih] = [innerWidth, innerHeight]
  const images = Array.from({ length: 3 }, () => new Image(iw, ih))
  const imagePromises = images.map($img => new Promise(r => $img.onload = r))  
  const $tmpCanvas = document.createElement('canvas')
  const cx = $tmpCanvas.getContext('2d')

  $tmpCanvas.width = iw
  $tmpCanvas.height = ih
  
  images[0].src = elemBg.includes('url("https://')
    // It's just an average color of the initial background and not the image itself 
    // because I couldn't find a way to render a non-cors image onto a canvas
    // (I guess it's impossible).
    // Base64 inlining is not an option since the image is huge.
    ? getDataUrlForColor(
      document.getElementById('menu-list').children[2].style.getPropertyValue('--c')
    )
    : elemBg.includes('data:image')
      ? elemBg.match(/^url\(['"]?([^'"]+)['"]?\)$/)[1]
      : elemBg.includes('gradient')
        ? (
            'data:image/svg+xml,' + encodeURIComponent(
              `<svg xmlns="http://www.w3.org/2000/svg" width="${iw}" height="${ih}">
                <foreignObject width="100%" height="100%">
                  <div
                    xmlns="http://www.w3.org/1999/xhtml"
                    style='background-image:${elemBg};width:100%;height:100%;'>
                  </div>
                </foreignObject>
              </svg>`
            )
          )
        : getDataUrlForColor(elemBg)
  

  images[1].src = getDataUrlForColor(canvasBg)
  images[2].src = $canvas.toDataURL()

  await Promise.all(imagePromises)

  images.map($img => cx.drawImage($img, 0, 0))

  return $tmpCanvas.toDataURL()
  
  function getDataUrlForColor (color) {
    const cxRectArgs = [0, 0, iw, ih]

    cx.fillStyle = color
    cx.fillRect(...cxRectArgs)

    const dataUrl = $tmpCanvas.toDataURL()

    cx.clearRect(...cxRectArgs)

    return dataUrl
  }
}

// Change only what should be changed,
// not just 'innerHTML' the whole thing
function changeHeading (newHeadingText) {
  const newHeadingLen = newHeadingText.length
  const curHeadingLen = $heading.children.length
  const letterWrappers = [...$heading.children].slice(0, Math.min(newHeadingLen, curHeadingLen))

  if (newHeadingLen < curHeadingLen) {
    [...$heading.children].slice(newHeadingLen).forEach($child => $child.remove())
  } else if (newHeadingLen > curHeadingLen) {
    const domToAppend = newHeadingText.slice(curHeadingLen)
      .map(letter => `<span class="slide-letter"><span>${letter}</span></span>`)
      .join('')

    $heading.insertAdjacentHTML('beforeend', domToAppend)
  }

  for (const i in letterWrappers) {
    // It's the fastest way to update existing text
    // https://twitter.com/_developit/status/997132016612270081
    letterWrappers[i].children[0].firstChild.data = newHeadingText[i]
  }
}

function revealHeading () {
  $heading.className = 'heading'
  setTimeout(() => $heading.classList.add('heading--in'), 0)
}

function hideToggleBtn () {
  $toggleBtn.classList.add('menu-toggle--hidden')
}

function showToggleBtn () {
  once($toggleBtn, 'transitionend', function () {
    this.classList.remove('menu-toggle--hidden')
  })
}

function once ($el, event, cb) {
  $el.addEventListener(event, function callback (e) {
    cb.call($el, e)
    this.removeEventListener(event, callback)
  })
}
  
// Start the show

const $toggleBtn = document.getElementById('menu-toggle')
const $heading = document.getElementById('heading')

$toggleBtn.addEventListener('click', () => {
  hideToggleBtn()
  menu.toggle()
})

const menu = new Menu({
  $menu: document.getElementById('menu'),

  blockSize: 10,
  scalingBlocksAmount: 5,
  transitionEasing: circInOut,
  moveEasing: power3Out,

  // Hooks
  async onMenuTransitionFinish ($canvas, $clickedItem) {
    changeHeading($clickedItem.innerText.split(' '))
    revealHeading()

    const $content = document.getElementById('content')
    $content.style.backgroundImage = `url(${await blendImages($content, $canvas)})`
  }, 

  onMenuOpen () {
    $heading.className = 'heading heading--out'
  },

  onMenuClose () {
    setTimeout(() => $heading.className = 'heading heading--in', 300)

    $toggleBtn.classList.remove('menu-toggle--opened')
    showToggleBtn()
  },

  onMenuAssemble () {
    $toggleBtn.classList.add('menu-toggle--opened')
    showToggleBtn()
  },

  onMenuItemClick: hideToggleBtn
})

// Demo stuff

const timer = setTimeout(() => {
  $toggleBtn.classList.add('menu-toggle--hidden')
  menu.open()
}, 2000)

once(document, 'mousemove', () => clearTimeout(timer))

              
            
!
999px

Console