css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

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.

            
              .container
  // Any font from Google Fonts should work here
  .granim(data-font='Lobster') Granim.js
            
          
!
            
              @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;
  }
}
            
          
!
            
              /* 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
🕑 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.
Loading ..................

Console