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

              
                .container
  // Any font from Google Fonts should work here
  .granim(data-font='Lobster') Granim.js
              
            
!

CSS

              
                @include theme($bg-dark-blue);

.container {
  display: flex;
  height: 100%;
  flex-direction: column;
  justify-content: center;
  padding: 20px;
}

.granim {
  position: relative;
  margin: auto;
  background: $bg;
  // Font Size must be in px
  font-size: 128px;
  
  .mask, canvas {
    display: block;
    width: inherit;
    height: inherit;
  }
  
  .mask {
    position: absolute;
    top: -1px;
    left: -1px;
    text-indent: -9999px;
    box-sizing: content-box;
  }
}
              
            
!

JS

              
                /* jshint esversion: 6, asi: true, boss: true */

let loadedFonts = ['Serif']

CanvasRenderingContext2D.prototype.getTextHeight = function (text) {
  let body = $mm('body')
  let dummy = $mm('<div>', { style: this.font })
  dummy.append(document.createTextNode(text))
  body.append(dummy)
  let result = dummy.offsetHeight
  body.removeChild(dummy)
  return result
}

let els = $mm.findAll('.granim').forEach(el => {
  let text = el.text
  el.text = null
  
  let bg = el.getStyle('background-color') || 'white'
  
  let canvasEl = $mm('<canvas>').appendTo(el)
  let maskEl = $mm('<div>', {
    class: 'mask',
    html: text,
    style: {
      border: `2px solid ${bg}`
    }
  }).appendTo(el)
  
  // Create the mask
  let fontSize = parseInt(el.getStyle('font-size')) || 32
  let fontFamily = el.data('font') || 'Open Sans'
  
  textMask(text, fontSize, fontFamily, bg).then(mask => {
    // Resize the container to fit the mask
    el.style.width = `${mask.attr('width')}px`
    el.style.height = `${mask.attr('height')}px`

    // Use the canvas as the background image
    maskEl.style.backgroundImage = `url(${mask.toDataURL()})`
  })
  
  new Granim({
    element: canvasEl,
    direction: 'left-right',
    opacity: [1, 1],
    states : {
      'default-state': {
        gradients: [
          ['#EB3349', '#F45C43'],
          ['#FF8008', '#FFC837'],
          ['#4CB8C4', '#3CD3AD'],
          ['#24C6DC', '#514A9D'],
          ['#FF512F', '#DD2476'],
          ['#DA22FF', '#9733EE']
        ],
        transitionSpeed: 2000
      }
    }
  })
})

// Creates a mask canvas for the given parameters
function textMask (text, fontSize, font, bg) {
  const canvas = $mm('<canvas>')
  const ctx = canvas.getContext('2d')

  // Looks complicated, but boils down to checking if the font is loaded
  // and loading it if it's not before creating the mask image
  return new Promise((resolve, reject) => {
    function createMask () {
      ctx.font = `${fontSize}px '${font}'`

      const textWidth = ctx.measureText(text).width
      const textHeight = ctx.getTextHeight(text)

      canvas.attr('width', textWidth + fontSize / 5)
      canvas.attr('height', fontSize + fontSize * 2 / 5)

      ctx.textBaseline = 'hanging'
      ctx.font = `${fontSize}px ${font}`

      ctx.fillStyle = bg
      ctx.fillRect(0, 0, canvas.width, canvas.height)

      ctx.globalCompositeOperation = 'xor'
      ctx.fillText(text, fontSize / 10, fontSize / 5)

      resolve(canvas)
    }
    
    if (loadedFonts.includes(font)) {
      createMask()
    } else {
      WebFont.load({
        google: {
          families: [font]
        },
        active: () => {
          loadedFonts.push(font)
          createMask()
        }
      })
    }
  })
}
              
            
!
999px

Console