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.

            
              canvas
p loading audio...

            
          
!
            
              body
  background: #000
  
canvas, p
  position: absolute
  top: 50%
  left: 50%
  transform: translate(-50%, -50%)
  
canvas
  cursor: pointer
  
p
  pointer-events: none
  margin: 4px 0 0 1px
  font-family: monospace
  color: #fff
  
  &:not(.fa)::after
    content: '💧'
    position: absolute
    font-size: 24px
    top: 124px
    left: 6px
  
  &.fa
    font-size: 24px
    color: #000

            
          
!
            
              !function () {
  // play with these
  var MIN_RADIUS = 300;
  var JITTER_RANGE = 200;
  var NUM_NODES = 256; // only 1/2 of these are actually drawn
  var COLOR = [255, 255, 255];
  var SMOOTHING_TIME_CONSTANT = 0.6; // 0-1
  
  // derived
  var center = MIN_RADIUS + JITTER_RANGE;
  var size = center * 2;
  // the bottom 1/8 and top 3/8 of this song are pretty boring...
  var i0 = NUM_NODES / 8;
  var i1 = NUM_NODES * 5 / 8;
  var range = i1 - i0;
  
  // shared state
  var hovered = false;
  
  // math
  var PI = Math.PI;
  var sin = Math.sin;
  var cos = Math.cos;

  // canvas
  var canvas = document.querySelector('canvas');
  var ctx = canvas.getContext('2d');
  canvas.height = canvas.width = size;
  ctx.lineWidth = 2;
  ctx.strokeStyle = 'rgb(' + COLOR + ')';
  
  var leftOnly = ctx.createLinearGradient(0, 0, size, 0);
  leftOnly.addColorStop(0, '#fff');
  leftOnly.addColorStop(0.5, '#fff');
  leftOnly.addColorStop(0.5, 'transparent');
  
  // helper function
  function dbToXY (db, i) {
    var r = MIN_RADIUS + db / 255 * JITTER_RANGE;
    var theta = 2*PI * (i / range + 1/4);
    
		return {
      x: r * cos(theta) + center,
      y: r * sin(theta) + center,
    };
  }
  
  function smoothCurveTo (db1, db2, i) {
    var coords1 = dbToXY(db1, i);
    // midpoint between db1 and db2
    var coords2 = dbToXY((db1 + db2) / 2, i + 0.5);

    ctx.quadraticCurveTo(coords1.x, coords1.y, coords2.x, coords2.y);
  }
  
  // helper function
  function drawX (x, y, r, width) {
    ctx.save();
    ctx.beginPath();
    ctx.lineWidth = width;
    ctx.moveTo(x - r, y - r);
    ctx.lineTo(x + r, y + r);
    ctx.moveTo(x - r, y + r);
    ctx.lineTo(x + r, y - r);
    ctx.stroke();
    ctx.restore();
  }

  // main loop
  function update (analyser, freqArray) {
    var i;
    ctx.clearRect(0, 0, size, size);
    analyser.getByteFrequencyData(freqArray);
    
    var average = 0;
    for (i = i0; i < i1; ++i) {
      average += freqArray[i]; 
    }
    average /= range;
    
    // draw a straight line from i0 to i1 and add it to the
    // resultant shape to ensure the lo and hi nodes meet smoothly
    var lo = freqArray[i0];
    var hi = freqArray[i1];
    var slope = lo - hi;
    
    // also ensure that our average radius never changes
    var offset = (average + slope) / 2;

    ctx.beginPath();
    var firstDb = freqArray[i0] - offset;
    var lastDb = freqArray[i1 - 1] + (range - 1) * slope / range - offset;
    var initialCoords = dbToXY((lastDb + firstDb) / 2, range - 0.5);
    ctx.moveTo.apply(ctx, [initialCoords.x, initialCoords.y]);
    
    var prevDb, db = firstDb;
    for (i = i0 + 1; i < i1; ++i) {
      prevDb = db;
      db = freqArray[i] + (i - i0) * slope / range - offset;
      smoothCurveTo(prevDb, db, i - i0 - 1);
    }
    smoothCurveTo(lastDb, firstDb, range - 1);    
    ctx.stroke();


    // draw face
    if (hovered) {
      ctx.fill();
    } else {
      // eyes
      var x1 = center - MIN_RADIUS / 2.5;
      var x2 = center + MIN_RADIUS / 2.5;
      drawX(x1, x2 - 20, 16, 6);
      drawX(x2, x2 - 20, 16, 6);
      
      // mouth
      ctx.beginPath();
      ctx.moveTo(center - 20, x2 + 10);
      ctx.lineTo(center + 20, x2 + 10);
      ctx.stroke();
    }

    requestAnimationFrame(update.bind(this, analyser, freqArray));
  }
  
  function loadSound (url, cb) {
    var request = new XMLHttpRequest();
    request.open('GET', url, true);
    request.responseType = 'arraybuffer';
    request.onload = function () { cb(request.response); };
    request.send();
  }
  
  // load the mp3 and initialize our visualizer
  loadSound('//katiebaca.com/tutorial/odd-look.mp3', function (res) {
    var audioContext = new (window.AudioContext || window.webkitAudioContext)();
    audioContext.decodeAudioData(res, function (buffer) {
      var analyser = audioContext.createAnalyser();
      var freqArray = new Uint8Array(analyser.frequencyBinCount);
      var sourceNode = audioContext.createBufferSource();
      analyser.smoothingTimeConstant = SMOOTHING_TIME_CONSTANT;
      analyser.fftSize = NUM_NODES * 2;
      analyser.minDecibels = -90;
      analyser.maxDecibels = -10;
      sourceNode.buffer = buffer;
      analyser.connect(audioContext.destination);
      sourceNode.connect(analyser, freqArray);
      sourceNode.start(0);
      update(analyser, freqArray);
      
      // add play/pause control
      var playing = true;
      var control = document.querySelector('p');
      control.textContent = '';
      control.className = '';
      
      canvas.addEventListener('click', function () {
        playing = !playing;
        
        // this doesn't actually pause anything, just fakes it...
				sourceNode[(playing ? '' : 'dis') + 'connect'](analyser);
        control.className = 'fa fa-' + (playing ? 'pause' : 'play');
			}, false);
      
      canvas.addEventListener('mouseenter', function () {
				ctx.fillStyle = 'rgba(' + COLOR + ', 0.24)';
        control.className = 'fa fa-' + (playing ? 'pause' : 'play');
        hovered = true;
			}, false);
      
      canvas.addEventListener('mouseleave', function () {
				ctx.fillStyle = 'rgba(' + COLOR + ', 0)';
        control.className = '';
        hovered = false;
			}, false);
    });
  });
}();

            
          
!
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