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
  h1 Mechanical Waves & Sound
  
javascript:
  /*! simplex-noise.js: copyright 2012 Jonas Wagner, licensed under a MIT license. See https://github.com/jwagner/simplex-noise.js for details */
  !function(){"use strict";function SimplexNoise(random){random||(random=Math.random),this.p=new Uint8Array(256),this.perm=new Uint8Array(512),this.permMod12=new Uint8Array(512);for(var i=0;256>i;i++)this.p[i]=256*random();for(i=0;512>i;i++)this.perm[i]=this.p[255&i],this.permMod12[i]=this.perm[i]%12}var F2=.5*(Math.sqrt(3)-1),G2=(3-Math.sqrt(3))/6,F3=1/3,G3=1/6,F4=(Math.sqrt(5)-1)/4,G4=(5-Math.sqrt(5))/20;SimplexNoise.prototype={grad3:new Float32Array([1,1,0,-1,1,0,1,-1,0,-1,-1,0,1,0,1,-1,0,1,1,0,-1,-1,0,-1,0,1,1,0,-1,1,0,1,-1,0,-1,-1]),grad4:new Float32Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]),noise2D:function(xin,yin){var i1,j1,permMod12=this.permMod12,perm=this.perm,grad3=this.grad3,n0=0,n1=0,n2=0,s=(xin+yin)*F2,i=Math.floor(xin+s),j=Math.floor(yin+s),t=(i+j)*G2,X0=i-t,Y0=j-t,x0=xin-X0,y0=yin-Y0;x0>y0?(i1=1,j1=0):(i1=0,j1=1);var x1=x0-i1+G2,y1=y0-j1+G2,x2=x0-1+2*G2,y2=y0-1+2*G2,ii=255&i,jj=255&j,t0=.5-x0*x0-y0*y0;if(t0>=0){var gi0=3*permMod12[ii+perm[jj]];t0*=t0,n0=t0*t0*(grad3[gi0]*x0+grad3[gi0+1]*y0)}var t1=.5-x1*x1-y1*y1;if(t1>=0){var gi1=3*permMod12[ii+i1+perm[jj+j1]];t1*=t1,n1=t1*t1*(grad3[gi1]*x1+grad3[gi1+1]*y1)}var t2=.5-x2*x2-y2*y2;if(t2>=0){var gi2=3*permMod12[ii+1+perm[jj+1]];t2*=t2,n2=t2*t2*(grad3[gi2]*x2+grad3[gi2+1]*y2)}return 70*(n0+n1+n2)},noise3D:function(xin,yin,zin){var n0,n1,n2,n3,i1,j1,k1,i2,j2,k2,permMod12=this.permMod12,perm=this.perm,grad3=this.grad3,s=(xin+yin+zin)*F3,i=Math.floor(xin+s),j=Math.floor(yin+s),k=Math.floor(zin+s),t=(i+j+k)*G3,X0=i-t,Y0=j-t,Z0=k-t,x0=xin-X0,y0=yin-Y0,z0=zin-Z0;x0>=y0?y0>=z0?(i1=1,j1=0,k1=0,i2=1,j2=1,k2=0):x0>=z0?(i1=1,j1=0,k1=0,i2=1,j2=0,k2=1):(i1=0,j1=0,k1=1,i2=1,j2=0,k2=1):z0>y0?(i1=0,j1=0,k1=1,i2=0,j2=1,k2=1):z0>x0?(i1=0,j1=1,k1=0,i2=0,j2=1,k2=1):(i1=0,j1=1,k1=0,i2=1,j2=1,k2=0);var x1=x0-i1+G3,y1=y0-j1+G3,z1=z0-k1+G3,x2=x0-i2+2*G3,y2=y0-j2+2*G3,z2=z0-k2+2*G3,x3=x0-1+3*G3,y3=y0-1+3*G3,z3=z0-1+3*G3,ii=255&i,jj=255&j,kk=255&k,t0=.6-x0*x0-y0*y0-z0*z0;if(0>t0)n0=0;else{var gi0=3*permMod12[ii+perm[jj+perm[kk]]];t0*=t0,n0=t0*t0*(grad3[gi0]*x0+grad3[gi0+1]*y0+grad3[gi0+2]*z0)}var t1=.6-x1*x1-y1*y1-z1*z1;if(0>t1)n1=0;else{var gi1=3*permMod12[ii+i1+perm[jj+j1+perm[kk+k1]]];t1*=t1,n1=t1*t1*(grad3[gi1]*x1+grad3[gi1+1]*y1+grad3[gi1+2]*z1)}var t2=.6-x2*x2-y2*y2-z2*z2;if(0>t2)n2=0;else{var gi2=3*permMod12[ii+i2+perm[jj+j2+perm[kk+k2]]];t2*=t2,n2=t2*t2*(grad3[gi2]*x2+grad3[gi2+1]*y2+grad3[gi2+2]*z2)}var t3=.6-x3*x3-y3*y3-z3*z3;if(0>t3)n3=0;else{var gi3=3*permMod12[ii+1+perm[jj+1+perm[kk+1]]];t3*=t3,n3=t3*t3*(grad3[gi3]*x3+grad3[gi3+1]*y3+grad3[gi3+2]*z3)}return 32*(n0+n1+n2+n3)},noise4D:function(x,y,z,w){var n0,n1,n2,n3,n4,perm=(this.permMod12,this.perm),grad4=this.grad4,s=(x+y+z+w)*F4,i=Math.floor(x+s),j=Math.floor(y+s),k=Math.floor(z+s),l=Math.floor(w+s),t=(i+j+k+l)*G4,X0=i-t,Y0=j-t,Z0=k-t,W0=l-t,x0=x-X0,y0=y-Y0,z0=z-Z0,w0=w-W0,rankx=0,ranky=0,rankz=0,rankw=0;x0>y0?rankx++:ranky++,x0>z0?rankx++:rankz++,x0>w0?rankx++:rankw++,y0>z0?ranky++:rankz++,y0>w0?ranky++:rankw++,z0>w0?rankz++:rankw++;var i1,j1,k1,l1,i2,j2,k2,l2,i3,j3,k3,l3;i1=rankx>=3?1:0,j1=ranky>=3?1:0,k1=rankz>=3?1:0,l1=rankw>=3?1:0,i2=rankx>=2?1:0,j2=ranky>=2?1:0,k2=rankz>=2?1:0,l2=rankw>=2?1:0,i3=rankx>=1?1:0,j3=ranky>=1?1:0,k3=rankz>=1?1:0,l3=rankw>=1?1:0;var x1=x0-i1+G4,y1=y0-j1+G4,z1=z0-k1+G4,w1=w0-l1+G4,x2=x0-i2+2*G4,y2=y0-j2+2*G4,z2=z0-k2+2*G4,w2=w0-l2+2*G4,x3=x0-i3+3*G4,y3=y0-j3+3*G4,z3=z0-k3+3*G4,w3=w0-l3+3*G4,x4=x0-1+4*G4,y4=y0-1+4*G4,z4=z0-1+4*G4,w4=w0-1+4*G4,ii=255&i,jj=255&j,kk=255&k,ll=255&l,t0=.6-x0*x0-y0*y0-z0*z0-w0*w0;if(0>t0)n0=0;else{var gi0=perm[ii+perm[jj+perm[kk+perm[ll]]]]%32*4;t0*=t0,n0=t0*t0*(grad4[gi0]*x0+grad4[gi0+1]*y0+grad4[gi0+2]*z0+grad4[gi0+3]*w0)}var t1=.6-x1*x1-y1*y1-z1*z1-w1*w1;if(0>t1)n1=0;else{var gi1=perm[ii+i1+perm[jj+j1+perm[kk+k1+perm[ll+l1]]]]%32*4;t1*=t1,n1=t1*t1*(grad4[gi1]*x1+grad4[gi1+1]*y1+grad4[gi1+2]*z1+grad4[gi1+3]*w1)}var t2=.6-x2*x2-y2*y2-z2*z2-w2*w2;if(0>t2)n2=0;else{var gi2=perm[ii+i2+perm[jj+j2+perm[kk+k2+perm[ll+l2]]]]%32*4;t2*=t2,n2=t2*t2*(grad4[gi2]*x2+grad4[gi2+1]*y2+grad4[gi2+2]*z2+grad4[gi2+3]*w2)}var t3=.6-x3*x3-y3*y3-z3*z3-w3*w3;if(0>t3)n3=0;else{var gi3=perm[ii+i3+perm[jj+j3+perm[kk+k3+perm[ll+l3]]]]%32*4;t3*=t3,n3=t3*t3*(grad4[gi3]*x3+grad4[gi3+1]*y3+grad4[gi3+2]*z3+grad4[gi3+3]*w3)}var t4=.6-x4*x4-y4*y4-z4*z4-w4*w4;if(0>t4)n4=0;else{var gi4=perm[ii+1+perm[jj+1+perm[kk+1+perm[ll+1]]]]%32*4;t4*=t4,n4=t4*t4*(grad4[gi4]*x4+grad4[gi4+1]*y4+grad4[gi4+2]*z4+grad4[gi4+3]*w4)}return 27*(n0+n1+n2+n3+n4)}},"undefined"!=typeof define&&define.amd&&define(function(){return SimplexNoise}),"undefined"!=typeof exports?exports.SimplexNoise=SimplexNoise:"undefined"!=typeof window&&(window.SimplexNoise=SimplexNoise),"undefined"!=typeof module&&(module.exports=SimplexNoise)}();
  
    // Typed array .fill polyfill
  if (typeof Uint16Array.prototype.fill !== 'function') {
      Uint16Array.prototype.fill = function(value) {
          var i = this.length;
          while (i--) {
              this[i] = value;
          }
      }
  }
            
          
!
            
              $background: #1e202e

html, body
  background: #aaa
  height: 100%
  width: 100%
  
body
  align-items: center
  display: flex
  justify-content: center
  margin: 0

.container
  background: $background
  border: 2px solid #aaa
  box-shadow: 0 0 12px #444
  box-sizing: border-box
  height: 480px
  max-height: 90vh
  max-width: 90vh
  overflow: hidden
  position: relative
  width: 480px
  
  canvas
    position: absolute
    top: 0
    bottom: 0
    left: 0
    right: 0
  
  h1
    background: rgba(#000, 0.33)
    bottom: 6px
    box-shadow: 0 0 10px 10px rgba(#000, 0.33)
    color: #fff
    display: inline-block
    font-family: sans-serif
    font-size: 16px
    left: 12px
    letter-spacing: 3px
    margin: 0
    pointer-events: none
    position: absolute
    text-transform: uppercase
    width: 100%
    z-index: 1
    
            
          
!
            
              // Constants
const BACKGROUND_COLOR = '#1e202e';
const FOREGROUND_COLOR = '#5b6b87';
const LINE_WIDTH = 2;
const PEAK_AGE = 20;
const DECAY_LENGTH_FACTOR = 20;
const DECAY_WIDTH_FACTOR = 1 / 25;
const SPEED = 1;
const WOBBLE_SPEED = 1 / 300;
const LINE_SPACING_PX = 8;
const NODE_SPACING_PX = 10;
const NEIGHBOR_GAP = 3;
const AMPLITUDE_PX = 3;
const PEAK_HEIGHT_PX = 42;
const DEBUG_COLORS = false;

// State
// Keeping the baseline offset decoupled from `t` lets us transition smoothly
// to !isMoving, etc
let t = 0;
let baselineOffset = 0;
let phase = 0;
let isMoving = true;
let peak = {};

// Simplex noise kicks Perlin noise's butt! Don't let the name fool you :D
const simplex = new SimplexNoise();

// DOM things
const container = document.querySelector('.container');
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const h = canvas.height = container.offsetHeight;
const w = canvas.width = container.offsetWidth;
container.appendChild(canvas);

peak.x = w / 2;
peak.y = h / 2;

canvas.addEventListener('mousemove', e => peak = mouseCoords(e));
canvas.addEventListener('click', e => isMoving = !isMoving);

ctx.fillStyle = BACKGROUND_COLOR;
ctx.strokeStyle = FOREGROUND_COLOR;
ctx.lineWidth = LINE_WIDTH;

// Each line is a typed array of node height values.
const MAX_INT_16_VALUE = Math.pow(2, Int16Array.BYTES_PER_ELEMENT * 8 - 1) - 1;
const numNodes = Math.floor(w / NODE_SPACING_PX) + 1;
const numLines = Math.floor(h / LINE_SPACING_PX) + 1 +
    Math.ceil(PEAK_HEIGHT_PX / LINE_SPACING_PX);
const lines = Array.from({length: numLines}, () => {
    const buffer = new ArrayBuffer(numNodes * Int16Array.BYTES_PER_ELEMENT);
    return new Int16Array(buffer);
});

// We also record the ages of peak nodes on a line.
const linePeaks = Array.from({length: numLines}, () => {
    const buffer = new ArrayBuffer(numNodes * Uint16Array.BYTES_PER_ELEMENT);
    return new Uint16Array(buffer);
});

const hTotal = numLines * LINE_SPACING_PX;

// Self-executing game loop. Here we go!
(function step() {
    // Line & node index for the center of our bell curve.
    const peakNode = {
        x: mod(Math.ceil(peak.x / NODE_SPACING_PX), numNodes),
        y: mod(Math.ceil(peak.y / LINE_SPACING_PX) + 1, numLines),
    };

    // Clear the last frame
    ctx.clearRect(0, 0, w, h);

    if (isMoving) {
        ++baselineOffset;

        if (t % LINE_SPACING_PX === 0) {
            // Whenever a line shifts off the screen's top, we move it to the
            // front of our array. `phase` keeps track of the array's offset.
            // We could be more clever about this and keep the array intact,
            // but this method has the advantage of matching idx to draw order.
            lines.unshift(lines.pop());
            phase = mod((phase + 1), numLines);
            linePeaks[phase].fill(0);
            baselineOffset = 0;
        }
    }

    // Draw each line sequentially. A few definitions, before we get into it:
    //
    // lineIdx: Loop index. Represents the order things are drawn to the canvas
    //          in, which means it holds a steady y position on the canvas,
    //          independent of phase.
    // phase: Entries in our `lines` array are frequently shifted from the back
    //        of the array to the front. `phase` records how many times the
    //        array has been shifted so we can keep track of specific lines.
    // adjustedLineIdx: The actual line index that should be drawn on this
    //                  step. Represents a single characteristic line that
    //                  evolves over time via the simplex function.
    // peakNode: line (y) and node (x) coordinates of wherever the mouse is.

    for (let lineIdx = 0; lineIdx < numLines; ++lineIdx) {
        // Update our nodes with the next simplex value times a gaussian curve
        // centred on peakNode.
        const adjustedLineIdx = mod(lineIdx + phase, numLines);
        const nodes = lines[adjustedLineIdx];
        const peakNodes = linePeaks[adjustedLineIdx];
        const isHighlighted = peakNode.y === lineIdx;

        if (isHighlighted && !peakNodes[peakNode.x]) {
            let newAge = 1;
            for (let i = peakNode.x - NEIGHBOR_GAP, _len = peakNode.x + NEIGHBOR_GAP; i < _len; ++i) {
                if (peakNodes[i]) {
                    newAge = 0;
                    break;
                }
            }
            peakNodes[peakNode.x] = newAge;
        }

        for (let nodeIdx = 0; nodeIdx < numNodes; ++nodeIdx) {
            const noise = simplex.noise3D(
                adjustedLineIdx, nodeIdx, t * SPEED * WOBBLE_SPEED);
            let peaksValue = 0;
            let numPeaks = 0;

            for (let peakNodeIdx = 0; peakNodeIdx < numNodes; ++peakNodeIdx) {
                const age = peakNodes[peakNodeIdx] * SPEED;
                if (age) {
                    ++numPeaks;
                    const ageDiff = age - PEAK_AGE;
                    const rising = ageDiff <= 0;
                    peaksValue += (noise + 1) / 2 * gaussian2d(
                        PEAK_HEIGHT_PX,

                        age,
                        nodeIdx - peakNodeIdx,

                        PEAK_AGE,
                        0,

                        10 * SPEED * (rising ? 1 : 1 + DECAY_LENGTH_FACTOR),
                        0.5 / SPEED * (rising ? 1 : 1 + ageDiff * DECAY_WIDTH_FACTOR * 2)
                    );
                }
            }

            // Normalize it. Commented out for now, because the abrupt jump
            // doesn't cut it.
            //
            // peaksValue /= numPeaks || 1;

            // Put some bounds on our node height.
            peaksValue = Math.max(Math.min(peaksValue, PEAK_HEIGHT_PX * 3), 0);

            nodes[nodeIdx] =
                Math.min(MAX_INT_16_VALUE, noise * AMPLITUDE_PX + peaksValue);
        }

        // Visual debugging is fun debugging : )
        if (DEBUG_COLORS) {
            if (false) 'noop';
            else if (adjustedLineIdx === 42) { ctx.strokeStyle = 'orange'; }
            else if (lineIdx === 42) { ctx.strokeStyle = 'magenta'; }
            else if (phase === lineIdx) { ctx.strokeStyle = 'cyan'; }
            else if (phase === 0) { ctx.strokeStyle = 'limegreen'; }
            else { ctx.strokeStyle = FOREGROUND_COLOR; }
        }

        // Draw the line
        const baseline =
            mod(lineIdx * LINE_SPACING_PX - baselineOffset, hTotal);
        ctx.beginPath();
        ctx.moveTo(0, baseline);
        ctx.lineTo(0, baseline - nodes[0]);
        for (let x = 1; x < numNodes - 1; ++x) {
            const y = nodes[x];
          
            const midX = x + 0.5;
            const midY = (y + nodes[x + 1]) / 2;
          
            // Rather than drawing straight lines between nodes, this gives us
            // a curve that *approximates* each node value. If we were trying
            // to represent real data, this wouldn't fly.
            ctx.quadraticCurveTo(x * NODE_SPACING_PX, baseline - y,
                              midX * NODE_SPACING_PX, baseline - midY);
        }
        ctx.lineTo(w, baseline);
        ctx.fill();
        ctx.stroke();

        // Increment the peak nodes' ages once we've drawn our line (Probably
        // nicer to set age = timestamp and compare against `t`, but this
        // works).
        for (let peakNodeIdx = 0; peakNodeIdx < numNodes; ++peakNodeIdx) {
            if (peakNodes[peakNodeIdx]) ++peakNodes[peakNodeIdx];
        }
    };

    // And around and around we go...
    t += 1;
    window.requestAnimationFrame(step);
})();

// Util functions
function mouseCoords({clientX, clientY}) {
    const {left, top} = canvas.getBoundingClientRect();
    return {
      x: clientX - left,
      y: clientY - top,
    };
}

// Proper modulo :-)
function mod(a, b) {
    return ((a % b) + b) % b;
}

function gaussian2d(a, x, y, x0, y0, sigmaX, sigmaY) {
    return a * Math.exp(
        - Math.pow(x - x0, 2) / 2 / Math.pow(sigmaX, 2)
        - Math.pow(y - y0, 2) / 2 / Math.pow(sigmaY, 2)
    );
}

            
          
!
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