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. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ 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

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

              
                <canvas id="canvas"></canvas>

<script>
// stats.js - http://github.com/mrdoob/stats.js
(function(f,e){"object"===typeof exports&&"undefined"!==typeof module?module.exports=e():"function"===typeof define&&define.amd?define(e):f.Stats=e()})(this,function(){var f=function(){function e(a){c.appendChild(a.dom);return a}function u(a){for(var d=0;d<c.children.length;d++)c.children[d].style.display=d===a?"block":"none";l=a}var l=0,c=document.createElement("div");c.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000";c.addEventListener("click",function(a){a.preventDefault();
u(++l%c.children.length)},!1);var k=(performance||Date).now(),g=k,a=0,r=e(new f.Panel("FPS","#0ff","#002")),h=e(new f.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var t=e(new f.Panel("MB","#f08","#201"));u(0);return{REVISION:16,dom:c,addPanel:e,showPanel:u,begin:function(){k=(performance||Date).now()},end:function(){a++;var c=(performance||Date).now();h.update(c-k,200);if(c>=g+1E3&&(r.update(1E3*a/(c-g),100),g=c,a=0,t)){var d=performance.memory;t.update(d.usedJSHeapSize/
1048576,d.jsHeapSizeLimit/1048576)}return c},update:function(){k=this.end()},domElement:c,setMode:u}};f.Panel=function(e,f,l){var c=Infinity,k=0,g=Math.round,a=g(window.devicePixelRatio||1),r=80*a,h=48*a,t=3*a,v=2*a,d=3*a,m=15*a,n=74*a,p=30*a,q=document.createElement("canvas");q.width=r;q.height=h;q.style.cssText="width:80px;height:48px";var b=q.getContext("2d");b.font="bold "+9*a+"px Helvetica,Arial,sans-serif";b.textBaseline="top";b.fillStyle=l;b.fillRect(0,0,r,h);b.fillStyle=f;b.fillText(e,t,v);
b.fillRect(d,m,n,p);b.fillStyle=l;b.globalAlpha=.9;b.fillRect(d,m,n,p);return{dom:q,update:function(h,w){c=Math.min(c,h);k=Math.max(k,h);b.fillStyle=l;b.globalAlpha=1;b.fillRect(0,0,r,m);b.fillStyle=f;b.fillText(g(h)+" "+e+" ("+g(c)+"-"+g(k)+")",t,v);b.drawImage(q,d+a,m,n-a,p,d,m,n-a,p);b.fillRect(d+n-a,m,a,p);b.fillStyle=l;b.globalAlpha=.9;b.fillRect(d+n-a,m,a,g((1-h/w)*p))}}};return f});
</script>
              
            
!

CSS

              
                #canvas {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
              
            
!

JS

              
                console.clear();

window.addEventListener("load", init);

function init() {

  const vertexShader = `

    attribute vec2 aVertexPosition;

    // tweening values
    attribute vec3 startColor;
    attribute vec3 endColor;
    attribute vec2 startPosition;
    attribute vec2 endPosition;
    attribute float startRotation;
    attribute float endRotation;
    attribute float startScale;
    attribute float endScale;
    attribute float startTime;
    attribute float duration;
    attribute float alphaStartTime;
    attribute float alphaDuration;

    uniform mat3 translationMatrix;
    uniform mat3 projectionMatrix;
    uniform float time;

    varying float vAlpha;
    varying vec3 vColor;

    float power1Out(float t) {
      return t * (2.0 - t);
    }

    vec2 rotate(vec2 v, float a) {
      float s = sin(a);
      float c = cos(a);
      mat2 m = mat2(c, s, -s, c);
      return m * v;
    }

    void main() {

      // progress and easing ratios
      float progress = clamp(time - startTime, 0.0,duration) / duration;
      float alphaProgress = clamp(time - alphaStartTime, 0.0, alphaDuration) / alphaDuration;
      float ratio = power1Out(progress);
      float alphaRatio = power1Out(alphaProgress);

      // interpolate values
      float scale = mix(startScale, endScale, ratio);
      float rotation = mix(startRotation, endRotation, ratio);
      float alpha = mix(1.0, 0.0, alphaRatio);
      vec3 color = sqrt(mix(startColor * startColor, endColor * endColor, ratio)); 
      vec2 pos = rotate(aVertexPosition * scale, rotation) + mix(startPosition, endPosition, ratio);

      // send values to fragment shader
      vAlpha = alpha;
      vColor = color; 

      gl_Position = vec4((projectionMatrix * translationMatrix * vec3(pos, 1.0)).xy, 0.0, 1.0);
    }
  `;

  const fragmentShader = `
    varying float vAlpha;
    varying vec3 vColor;

    void main() {
      gl_FragColor = vec4(vColor, vAlpha);     
    }
  `;

  // dat.GUI settings
  const settings = {
    minParticles: 10000,
    maxParticles: 1000000,
    numParticles: 50000,
    step: 10000
  };

  let vw = innerWidth;
  let vh = innerHeight;
  let halfW = vw / 2;
  let halfH = vh / 2;
  let triangles, boxes, gui, stats;

  const app = new PIXI.Application({
    view: document.querySelector("#canvas"),
    resizeTo: window,
    powerPreference: "high-performance",
    autoStart: false,
    antialias: true
  });

  const attributes = createAttributes({
    startColor: 3,
    endColor: 3,
    startPosition: 2,
    endPosition: 2,
    startRotation: 1,
    endRotation: 1,
    startScale: 1,
    endScale: 1,
    startTime: 1,
    duration: 1,
    alphaStartTime: 1,
    alphaDuration: 1
  });

  const uniforms = {
    time: 0
  };

  const shader = PIXI.Shader.from(vertexShader, fragmentShader, uniforms);

  const stride = attributes.stride;
  const randomColor = createColors();
  const radius = Math.max(halfW, halfH) * Math.SQRT2;
  const shapeSize = 8;

  let totalDuration = 0;

  triangles = createMesh(createTriangleVertices(shapeSize * 1.4));
  boxes = createMesh(createBoxVertices(shapeSize));

  app.stage.addChild(triangles, boxes);

  createUI();
  createAnimations();

  function createMesh({ positions, index }) {

    const geometry = new PIXI.Geometry()
      .addAttribute("aVertexPosition", positions, 2)
      .addIndex(index);

    geometry.instanced = true;
    geometry.instanceCount = settings.numParticles;

    const buffer = createBuffer();  
    attributes.addToGeometry(geometry, buffer);

    const state = new PIXI.State();  
    const mesh = new PIXI.Mesh(geometry, shader, state);
    state.blend = true;
    state.blendMode = PIXI.BLEND_MODES.NORMAL_NPM;

    mesh.position.set(halfW, halfH);

    return mesh;
  }

  function createBuffer() {

    const startTimes = [];

    for (let i = 0; i < 10; i += 0.01) {
      startTimes.push(i);
    }

    const getStartTime = gsap.utils.wrap(startTimes);

    const len = Math.round(settings.maxParticles / 2);  
    const buffer = new PIXI.Buffer(new Float32Array(len * stride));
    const data = buffer.data; 

    // interleave values in buffer
    for (let i = 0; i < len; i++) {

      let pos = i * stride;

      const startTime = getStartTime(i);
      const duration = random(1, 4);
      const endTime = startTime + duration;

      const angle = Math.random() * Math.PI * 2;  
      const dist = random(0, radius)
      const color1 = randomColor();
      const color2 = randomColor();

      if (endTime > totalDuration) {
        totalDuration = endTime;
      } 

      // start color
      data[pos++] = color1.r;
      data[pos++] = color1.g;
      data[pos++] = color1.b;

      // end color
      data[pos++] = color2.r;
      data[pos++] = color2.g;
      data[pos++] = color2.b;

      // start position
      buffer.data[pos++] = 0;
      buffer.data[pos++] = 0;

      // end position
      data[pos++] = Math.cos(angle) * radius;
      data[pos++] = Math.sin(angle) * radius;

      // start rotation
      data[pos++] = random(0, Math.PI);

      // end rotation
      data[pos++] = random(0, Math.PI * 10);

      // start scale
      data[pos++] = 0;

      // end scale
      data[pos++] = random(0, 2);

      // start time
      data[pos++] = startTime;

      // duration
      data[pos++] = duration;

      // alpha start time
      data[pos++] = startTime + duration * (1 - 0.25);

      // alpha duration
      data[pos++] = duration * 0.25;
    }

    return buffer;
  }

  function createAnimations() {

    const tl = gsap.timeline({
        repeat: -1,
        yoyo: true,
        defaults: {
          ease: "none",
          duration: totalDuration
        }      
      })
      .to(shader.uniforms, { time: totalDuration }, 0.5)
      .to(triangles, { rotation: Math.PI * 4 }, 0.5)
      .to(boxes, { rotation: Math.PI * 2 }, 0.5);

    gsap.ticker.add(() => {    
      app.renderer.render(app.stage);
      stats.update();
    });
  }

  function createUI() {

    gui = new dat.GUI();
    gui.add(settings, "numParticles", settings.minParticles, settings.maxParticles, settings.step)
      .name("Num Particles")
      .onChange(value => {
        value = Math.round(value / 2);
        triangles.geometry.instanceCount = value;
        boxes.geometry.instanceCount = value;
    });

    stats = new Stats();
    document.body.appendChild(stats.dom);
  }

  function random(min, max) {
    return min + (max - min) * Math.random();
  }

  function randomSign() {
    return Math.random() < 0.5 ? 1 : -1;
  }

  function createColors() {

    const colors = [];

    for (let i = 0; i < 360; i++) {
      const hsl = `hsl$(${i}, 90%, 60%)`;
      const split = gsap.utils.splitColor(hsl);
      colors.push({
        r: split[0] / 255,
        g: split[1] / 255,
        b: split[2] / 255,
      });
    }

    return gsap.utils.random(colors, true);
  }

  function createBoxVertices(size) {
    const positions = [
      -size, -size,
      size, -size, 
      size, size,
      -size, size
    ];

    return {
      positions,
      index: [0, 1, 2, 0, 2, 3]
    }
  }

  function createTriangleVertices(radius) {

    const angle  = 2 * Math.PI / 3;
    const positions = []; 

    for (let i = 0; i < 3; i++) {
      positions.push(radius * Math.sin(i * angle));
      positions.push(-radius * Math.cos(i * angle));
    }

    return {
      positions,
      index: [0, 1, 2]
    }
  }

  function createAttributes(sizes) {

    const attrs = {};  
    const keys = Object.keys(sizes);

    let stride = 0;

    keys.forEach(key => {

      const size = sizes[key];

      const offset = stride * 4; // 4 bytes
      stride += size;

      attrs[key] = {
        size, offset
      }
    });

    function addToGeometry(geometry, buffer) {

      keys.forEach(key => {

        const attr = attrs[key];

        geometry.addAttribute(
          key, 
          buffer, 
          attr.size, 
          false, 
          PIXI.TYPES.FLOAT, 
          4 * stride, // 4 bytes
          attr.offset, 
          true
        );  
      });

      return geometry;
    }

    return { stride, attrs, addToGeometry };
  }
}
              
            
!
999px

Console