Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

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

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

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

              
                .mount.js-mount

br

.controls
  .row
    .column.small-12
      h1 SVG Water 
      
      .row
        .column.small-6
          p
            button.button.expanded.js-play-pause pause 

        .column.small-6
          p
            button.button.expanded.js-stop reset 

      h5 
        | Progress:
        span.js-progress-output loading...

      p
        input(
          class="js-progress",
          type="range",
          min=0,
          max=1,
          value=0,
          step=0.001
        )
      
      .row
        .column.small-6
          h5 
            | No. of waves:
            span.js-num-waves-output loading...

          p
            input(
              class="js-num-waves",
              type="range",
              min=0,
              max=10,
              value=4
            )
            
        .column.small-6
          h5 
            | Duration:
            span.js-duration-output loading...

          p
            input(
              class="js-duration",
              type="range",
              min=0,
              max=60,
              value=30
            )
 
  .column.small-12
    .text--center
      a(href="https://codepen.io/larrybotha/", target="_blank") more like this
              
            
!

CSS

              
                $clr-purple: #734891;
$clr-purple-lt: #cc80c5;

html, body {
  height: auto;
}

body {
  background-image: linear-gradient(to bottom, $clr-purple-lt, $clr-purple);
  background-repeat: no-repeat;
  color: $clr-purple;
  padding-top: 1em;
}

a {
  color: $clr-purple;
  
  &:hover,
  &:focus { color: lighten($clr-purple, 5%);}
  
  &:active { color: lighten($clr-purple, 5%);}
}

input { width: 100%;}

.mount {
  & svg {
    display: block;
    max-width: 100%;
    margin: 0 auto;
  }
}

.row { max-width: 520px;}

.controls {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
}

.button {
  background-color: transparentize($clr-purple, .5);
  transition: all .15s ease-in-out;
  outline: 0;
  
  &:hover,
  &:focus {
    background-color: transparentize($clr-purple, .7);
  }
  
  &:active {
    background-color: transparentize($clr-purple, .3);
    transition: all 0s;
  }
}

.text--center { text-align:center;}
              
            
!

JS

              
                console.clear();
const log = (...args) => console.log(args);

const waveCanvasFactory = mountElem => {
  if (!mountElem || !('nodeType' in mountElem)) {
    throw new Error('no mount element provided');
  }

  const paths = {};
  let options = {
    width: 360,
    height: 360,
    type: 'svg',
    // onAnimEnd :: twoInstance -> null
    onAnimEnd: null,
    // onProgress :: Number -> null
    onProgress: null,
    gradients: [
      {
        from: '#f6bfbb',
        to: '#f08cba',
      },
      {
        from: '#f08cba',
        to: '#ff6a76',
      },
      {
        from: '#fbe0a3',
        to: '#f9eb6f',
      },
    ],
    waveVelocityRange: [1, 3],
  };
  let currProgress = 0;
  let duration = 10 * 1000;
  let isPlaying = false;
  let timeElapsed = 0;
  let waveData = [];
  let timeAtPause;
  let timeAtLastTick;
  let two;

  function init(opts) {
    options = Object.assign({}, options, opts);
    two = new Two({
      type: Two.Types[options.type],
      width: options.width,
      height: options.height,
    })
      .bind('resize', handleResize)
      .bind('update', animateWavesHorizontally)
      .play();

    two.appendTo(mountElem);
    setViewBox(options.width, options.height);
    initGroup();

    two.renderer.domElement.setAttribute(
      'style',
      `
        -moz-user-select:none;
        -ms-user-select:none;
        -webkit-user-select:none;
        user-select:none;
        -webkit-tap-highlight-color: rgba(0,0,0,0);
      `
    );
  }

  function initGroup() {
    paths.group = two.makeGroup();
    paths.group.translation.set(paths.group.translation.x, two.height);
  }

  function addWave(_, waveIndex) {
    const {width, height} = two;
    const waveWidth = Math.ceil(width);
    const numPeaks = 6;
    const bottomAnchors = [
      new Two.Anchor(waveWidth, height, 0, 0, 0, 0, Two.Commands.line),
      new Two.Anchor(0, height, 0, 0, 0, 0, Two.Commands.line),
    ];
    const waveAnchors = Array.apply(null, Array(numPeaks)).map((_a, i) => {
      const scalar = i % 2 === 0 ? -1 : 1;
      const y =
        i === 0 || i === numPeaks - 1
          ? 0
          : scalar *
            height *
            Math.floor(Math.random() * (5 - 1 + 1) + 1) /
            1000;
      const command = i === 0 ? 'move' : 'curve';
      const anchorPos = waveWidth / numPeaks * 0.45;

      return new Two.Anchor(
        waveWidth / (numPeaks - 1) * i,
        y * (1 + waveIndex),
        -anchorPos,
        0,
        anchorPos,
        0,
        Two.Commands[command]
      );
    });
    const vectors = waveAnchors.concat(bottomAnchors);
    const firstWave = new Two.Path(vectors, true, false, true);
    const secondWave = new Two.Path(vectors, true, false, true);
    const waveGroupHori = two.makeGroup();
    const waveGroupVert = two.makeGroup();

    waveGroupVert.add(firstWave, secondWave);
    waveGroupHori.add(waveGroupVert);
    paths.group.add(waveGroupHori);
    two.update();

    const waveYOffset = firstWave._renderer.elem.getBBox().y;
    const linearGradient = getWaveGradient(waveIndex);
    const velMax = Math.max.apply(null, options.waveVelocityRange);
    const velMin = Math.min.apply(null, options.waveVelocityRange);

    waveData[waveIndex] = {
      vel: new Two.Vector(Math.random() * (velMax - velMin + 1) + velMin, 0),
      width: waveWidth,
      yOffset: waveYOffset,
    };

    [firstWave, secondWave].map((wave, i) => {
      wave.noStroke();
      wave.translation.set(-waveWidth * i, -waveYOffset);
      wave.opacity = 0.7;
      wave.fill = linearGradient;

      return wave;
    });
  }

  function getWaveGradient(waveIndex) {
    const {gradients} = options;
    const gradient = gradients[waveIndex % gradients.length];

    return two.makeLinearGradient(
      two.width / 2,
      0,
      two.width / 2,
      two.height / 7,
      new Two.Stop(0, gradient.from),
      new Two.Stop(1, gradient.to)
    );
  }

  function drawWaves(numWaves) {
    if (paths.group) {
      paths.group.remove(paths.group.children);
    }

    Array.apply(null, Array(numWaves)).map(addWave);
    two.update();
  }

  function animateWavesVertically() {
    const timeDelta = performance.now() - timeAtLastTick;

    if (timeAtPause) {
      timeAtPause = undefined;
    }

    if (timeAtLastTick) {
      setTimeElapsed(timeElapsed + timeDelta);
    }

    timeAtLastTick = performance.now();

    if (timeElapsed + timeDelta > duration) {
      stop();
      setTimeElapsed(duration);

      if (typeof options.onAnimEnd === 'function') {
        options.onAnimEnd(two);
      }
    }
  }

  function animateWavesHorizontally() {
    const {group} = paths;

    if (group && group.children) {
      group.children.map((ch, i) => {
        if (!waveData[i]) return ch;

        const {vel, yOffset, width} = waveData[i];
        const shouldReset = ch.translation.x >= width;

        if (vel && !shouldReset) {
          ch.translation.addSelf(vel);
        } else {
          ch.translation.subSelf({x: width, y: 0});
        }

        return ch;
      });
    }
  }

  function getIsPlaying() {
    return isPlaying;
  }

  function setOptions(opts) {
    options = Object.assign({}, options, opts);
    reset();
  }

  function setDuration(dur) {
    duration = dur;
  }

  function setTimeElapsed(elapsed) {
    timeElapsed = elapsed;

    setProgress(elapsed / duration);
  }

  function setProgress(progress) {
    const {group} = paths;
    const {height} = two;
    const shouldUpdateTranslation = progress <= 1 && progress >= 0;

    currProgress = shouldUpdateTranslation ? progress : currProgress;

    if (group && shouldUpdateTranslation) {
      group.translation.set(
        group.translation.x,
        height - height * currProgress
      );

      if (typeof options.onProgress === 'function') {
        options.onProgress(currProgress);
      }
    }
  }

  function play() {
    timeAtLastTick = performance.now();
    isPlaying = true;
    bindVerticalWaveAnimation();
  }

  function pause() {
    timeAtPause = performance.now();
    isPlaying = false;
    unbindVerticalWaveAnimation();
  }

  function stop() {
    unbindVerticalWaveAnimation();
    isPlaying = false;
    setTimeElapsed(0);
    timeAtPause = undefined;
    timeAtLastTick = undefined;
  }

  function reset() {
    stop();
    destroyPaths();
    initGroup();
  }

  function bindVerticalWaveAnimation() {
    const isBound =
      two._events.update &&
      two._events.update.indexOf(animateWavesVertically) > -1;

    if (!isBound) {
      two.bind('update', animateWavesVertically);
    }
  }

  function unbindVerticalWaveAnimation() {
    const isBound =
      two._events.update &&
      two._events.update.indexOf(animateWavesVertically) > -1;

    if (isBound) {
      two.unbind('update', animateWavesVertically);
    }
  }

  function setViewBox(width, height) {
    two.renderer.domElement.setAttribute('viewBox', `0 0 ${width} ${height}`);
  }

  function handleResize() {
    setViewBox(two.width, two.height);
    drawWaves(paths.group.children.length);
    two.update();
  }

  function updateDims({height, width}) {
    two.width = parseInt(width, 10);
    two.height = parseInt(height, 10);
    two.trigger('resize');
  }

  function removeEvents() {
    Object.keys(two._events).map(event =>
      two._events[event].map(fn => two.unbind(event, fn))
    );
  }

  function destroyPaths() {
    delete paths.group;
    two.clear();
    two.update();
  }

  function destroy() {
    destroyPaths();
    removeEvents();

    return true;
  }

  return {
    destroy,
    drawWaves,
    getIsPlaying,
    init,
    pause,
    play,
    reset,
    setDuration,
    setTimeElapsed,
    stop,
    updateDims,
  };
};

const mount = document.querySelector('.js-mount');
const numWavesInput = document.querySelector('.js-num-waves');
const numWavesOutput = document.querySelector('.js-num-waves-output');
const durationInput = document.querySelector('.js-duration');
const durationOutput = document.querySelector('.js-duration-output');
const progressInput = document.querySelector('.js-progress');
const progressOutput = document.querySelector('.js-progress-output');
const playPauseButton = document.querySelector('.js-play-pause');
const stopButton = document.querySelector('.js-stop');

const waveCanvas = waveCanvasFactory(mount);
waveCanvas.init({
  width: window.innerWidth,
  height: window.innerHeight,
  onProgress: progress => {
    setProgressOutput(Math.round(progress * 1000) / 1000);
    progressInput.value = progress;
  },
  onAnimEnd() {
    playPauseButton.textContent = 'play';
  },
});
waveCanvas.drawWaves(numWavesInput.valueAsNumber);
waveCanvas.play();

function handleWavesChange(e) {
  const { value } = e.target;
  
  setNumWavesOutput(value);
  waveCanvas.drawWaves(+value);
}

function handleDurationChange(e) {
  const { value } = e.target;
  
  setDurationOutput(value);
  waveCanvas.setDuration(+value * 1000);
}

function handleProgressChange(e) {
  const { value } = e.target;
  const timeElapsed = durationInput.valueAsNumber * value * 1000;
  
  setProgressOutput(value);
  waveCanvas.setTimeElapsed(timeElapsed);
}

const handlePlayPauseClick = () => {
  const isPlaying = waveCanvas.getIsPlaying();
  const fnName = isPlaying ? 'pause' : 'play';

  waveCanvas[fnName]();

  playPauseButton.textContent = isPlaying ? 'play' : 'pause';
}

const handleStopClick = () => {
  waveCanvas.stop();

  playPauseButton.textContent = 'play';
}

const setNumWavesOutput = (value) => {
  numWavesOutput.textContent = ` ${value}`;
}

const setDurationOutput = (value) => {
  durationOutput.textContent = ` ${value}s`;
}

const setProgressOutput = (value) => {
  progressOutput.textContent = ` ${value}`;
}

numWavesInput.addEventListener('input', handleWavesChange);
durationInput.addEventListener('input', handleDurationChange);
progressInput.addEventListener('input', handleProgressChange);
playPauseButton.addEventListener('click', handlePlayPauseClick);
stopButton.addEventListener('click', handleStopClick);

numWavesInput.dispatchEvent(new Event('input'));
durationInput.dispatchEvent(new Event('input'));

window.addEventListener('resize', () => {
  waveCanvas.updateDims({
    width: window.innerWidth,
    height: window.innerHeight,
  });
});

              
            
!
999px

Console