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

              
                <div class="container-canvas"></div>

              
            
!

CSS

              
                body{
  margin: 0;
}

canvas{
  width: 100%;
  height: 100vh;
  display: block;
}
              
            
!

JS

              
                console.clear();

const snoise3d = `
//	Simplex 3D Noise 
//	by Ian McEwan, Ashima Arts
//
vec4 permute(vec4 x){return mod(((x*34.0)+1.0)*x, 289.0);}
vec4 taylorInvSqrt(vec4 r){return 1.79284291400159 - 0.85373472095314 * r;}

float snoise(vec3 v){ 
  const vec2  C = vec2(1.0/6.0, 1.0/3.0) ;
  const vec4  D = vec4(0.0, 0.5, 1.0, 2.0);

// First corner
  vec3 i  = floor(v + dot(v, C.yyy) );
  vec3 x0 =   v - i + dot(i, C.xxx) ;

// Other corners
  vec3 g = step(x0.yzx, x0.xyz);
  vec3 l = 1.0 - g;
  vec3 i1 = min( g.xyz, l.zxy );
  vec3 i2 = max( g.xyz, l.zxy );

  //  x0 = x0 - 0. + 0.0 * C 
  vec3 x1 = x0 - i1 + 1.0 * C.xxx;
  vec3 x2 = x0 - i2 + 2.0 * C.xxx;
  vec3 x3 = x0 - 1. + 3.0 * C.xxx;

// Permutations
  i = mod(i, 289.0 ); 
  vec4 p = permute( permute( permute( 
             i.z + vec4(0.0, i1.z, i2.z, 1.0 ))
           + i.y + vec4(0.0, i1.y, i2.y, 1.0 )) 
           + i.x + vec4(0.0, i1.x, i2.x, 1.0 ));

// Gradients
// ( N*N points uniformly over a square, mapped onto an octahedron.)
  float n_ = 1.0/7.0; // N=7
  vec3  ns = n_ * D.wyz - D.xzx;

  vec4 j = p - 49.0 * floor(p * ns.z *ns.z);  //  mod(p,N*N)

  vec4 x_ = floor(j * ns.z);
  vec4 y_ = floor(j - 7.0 * x_ );    // mod(j,N)

  vec4 x = x_ *ns.x + ns.yyyy;
  vec4 y = y_ *ns.x + ns.yyyy;
  vec4 h = 1.0 - abs(x) - abs(y);

  vec4 b0 = vec4( x.xy, y.xy );
  vec4 b1 = vec4( x.zw, y.zw );

  vec4 s0 = floor(b0)*2.0 + 1.0;
  vec4 s1 = floor(b1)*2.0 + 1.0;
  vec4 sh = -step(h, vec4(0.0));

  vec4 a0 = b0.xzyw + s0.xzyw*sh.xxyy ;
  vec4 a1 = b1.xzyw + s1.xzyw*sh.zzww ;

  vec3 p0 = vec3(a0.xy,h.x);
  vec3 p1 = vec3(a0.zw,h.y);
  vec3 p2 = vec3(a1.xy,h.z);
  vec3 p3 = vec3(a1.zw,h.w);

//Normalise gradients
  vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));
  p0 *= norm.x;
  p1 *= norm.y;
  p2 *= norm.z;
  p3 *= norm.w;

// Mix final noise value
  vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);
  m = m * m;
  return 42.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1), 
                                dot(p2,x2), dot(p3,x3) ) );
}

`;

const textureLoader = (opt) =>
  opt === "obj" ? new THREE.OBJLoader() : new THREE.TextureLoader();

class Webgl {
  constructor() {
    this.renderer = new THREE.WebGLRenderer({ antialias: true });
    this.scene = new THREE.Scene();
    this.camera = new THREE.PerspectiveCamera(
      45,
      innerWidth / innerHeight,
      1,
      1000
    );

    this.clock = new THREE.Clock();
    this.raycaster = new THREE.Raycaster();
    this.loader = textureLoader();

    this.init();
  }

  init() {
    const container = document.querySelector(".container-canvas");
    container.append(this.renderer.domElement);

    this.camera.position.set(0, 0, 2);

    this.renderer.setSize(innerWidth, innerHeight, false);

    const controls = new THREE.OrbitControls(
      this.camera,
      this.renderer.domElement
    );

    this.addRenderTarget();
    this.trail();
    this.addMesh();
  }

  initEvents() {
    window.addEventListener("mousemove", (e) => this.onMouseMove(e));
  }

  loadTextures(image) {
    return new Promise((resolve) => {
      this.loader.load(image, (texture) => {
        resolve(texture);
      });
    });
  }

  onMouseMove(e) {
    this.mouse = {
      x: e.clientX,
      y: innerHeight - e.clientY
    };

    this.planeTrail.material.uniforms.mouse.value = this.mouse;
  }

  addRenderTarget() {
    this.rt = new THREE.WebGLRenderTarget(innerWidth, innerHeight, {
      minFilter: THREE.LinearFilter,
      magFilter: THREE.LinearFilter,
      format: THREE.RGBAFormat,
      depthTest: false,
      depthBuffer: false,
      stencilBuffer: false
    });
    this.rt2 = this.rt.clone();

    this.rtScene = this.scene.clone();
    this.rtCamera = this.camera.clone();
  }

  trail() {
    const planeGeo = new THREE.PlaneBufferGeometry(1, 1);
    const planeMat = new THREE.ShaderMaterial({
      uniforms: {
        resolution: { value: new THREE.Vector2(innerWidth, innerHeight) },
        mouse: { value: { x: 0, y: 0 } },
        bufferTexture: { type: "t", value: this.rt.texture }
      },
      vertexShader: `
      varying vec2 vUv;    
  
      void main() {
        vUv = uv;

        vec4 mvPosition = modelViewMatrix * vec4(position,1.);
        gl_Position = projectionMatrix * mvPosition;
      }  
      `,
      fragmentShader: `
        uniform vec2 resolution;
        uniform vec2 mouse;
        uniform sampler2D bufferTexture;
      
        varying vec2 vUv;

        float getFactor(vec4 color){
          // Smoke diffuse
          //The size of a single pixel
	        float xPixel = 1.0 / resolution.x;
	        float yPixel = 1.0 / resolution.y;

	        vec4 rightColor = texture2D(bufferTexture,vec2(vUv.x - xPixel,vUv.y));
	        vec4 leftColor = texture2D(bufferTexture,vec2(vUv.x + xPixel,vUv.y));
	        vec4 upColor = texture2D(bufferTexture,vec2(vUv.x,vUv.y - yPixel));
	        vec4 downColor = texture2D(bufferTexture,vec2(vUv.x,vUv.y + yPixel));

          // Diffuse equation
          float directionColor = leftColor.r + rightColor.r + downColor.r * 3.0 + upColor.r;      
	        float factor = 0.128 * (directionColor - 6.0 * color.r);

          // We have to account for the low precision of texels
          float minimum = 0.003;
          if(factor >= -minimum && factor < 0.0) factor = -minimum;

          return factor;
        }

        void main(){
          vec2 st = (gl_FragCoord.xy - 0.5 * resolution) / min(resolution.x, resolution.y);
          vec2 mousepos = (mouse - 0.5 * resolution) / min(resolution.x, resolution.y);  

          vec4 color = texture2D(bufferTexture, vUv);

          float dist = clamp(1.0 - distance(mousepos, st) / 0.3, 0.0, 1.0);
          
          color += dist;
          color *= 0.9;

          color += getFactor(color);
        
          gl_FragColor = color;  
        }
      `
    });
    this.planeTrail = new THREE.Mesh(planeGeo, planeMat);
    this.setSize(this.rtCamera, this.planeTrail);
    this.rtScene.add(this.planeTrail);
  }

  async addMesh() {
    const texture = await this.loadTextures(
      "https://i.ibb.co/vhGJm7W/Meisje-met-de-parel.jpg"
    );

    const sphereGeom = new THREE.SphereBufferGeometry(0.12, 32, 32);
    const planeGeom = new THREE.PlaneBufferGeometry(25, 25, 105, 105);

    const { position, uv } = planeGeom.attributes;

    planeGeom.rotateX(-Math.PI / 2);

    this.instGeometry = new THREE.InstancedBufferGeometry();
    this.instGeometry.copy(sphereGeom);

    this.instGeometry.setAttribute(
      "instPosition",
      new THREE.InstancedBufferAttribute(position.array, 3)
    );

    this.instGeometry.setAttribute(
      "instUV",
      new THREE.InstancedBufferAttribute(uv.array, 2)
    );

    this.material = new THREE.MeshPhongMaterial({
      color: 0xd3d3d3,
      shininess: 100,
      transparent: true
    });

    this.uniforms = {
      time: { type: "f", value: 0 },
      texture: { type: "t", value: texture },
      resolution: {
        type: "v2",
        value: new THREE.Vector2(innerWidth, innerHeight)
      },
      bufferTexture: { type: "t", value: this.rt2.texture }
    };

    this.material.onBeforeCompile = (shader) => {
      shader.uniforms.time = this.uniforms.time;
      shader.uniforms.texture = this.uniforms.texture;
      shader.uniforms.bufferTexture = this.uniforms.bufferTexture;
      shader.uniforms.resolution = this.uniforms.resolution;

      /******************** Vertex Shader ********************/

      shader.vertexShader = `
             #define TAU 6.28318530718
             #define PI 3.14159265359
            
             uniform float time;
             uniform sampler2D texture;

             attribute vec3 instPosition;
             attribute vec2 instUV;

             varying vec2 vInstUV;
             varying vec2 vUv;
             varying vec4 vColor;
             varying vec3 vPosition;
        
             ${snoise3d}
             ${shader.vertexShader}`;

      const token = "#include <begin_vertex>";
      const customVertex = `
            vec3 offset = instPosition;       
  
            offset.xz -= snoise( vec3( instPosition.xz * 0.15, time * 0.25 ) ) * 0.15;

            vec4 color = texture2D( texture, instUV );

            offset.y += color.r;

            vec3 transformed = position + offset;
          
            vColor = color;
            vUv = uv;
            vPosition = transformed;
            vInstUV = instUV;`;

      shader.vertexShader = shader.vertexShader.replace(token, customVertex);

      /******************** Fragment Shader ********************/

      shader.fragmentShader = `
       
        uniform sampler2D bufferTexture;
        uniform vec2 resolution;

        varying vec2 vInstUV;
        varying vec2 vUv;
        varying vec4 vColor;
        varying vec3 vPosition;

        ${shader.fragmentShader}`;

      const token2 = "#include <map_fragment>";
      const customFragment = `
          #include <map_fragment> 

          vec2 st = gl_FragCoord.xy / resolution;

          vec2 instUV = vInstUV;
      
          vec4 bufferTrail = texture2D( bufferTexture, st );
          
          if( length(vColor.rgb) < 0.2 ) {
            discard;
          }

          vec4 color = vColor;

          color.rgb *= vPosition.y * vPosition.y;

          diffuseColor *= color * bufferTrail.r;
      `;

      shader.fragmentShader = shader.fragmentShader.replace(
        token2,
        customFragment
      );
    };

    this.instSpheres = new THREE.Mesh(this.instGeometry, this.material);
    this.instSpheres.rotation.x = Math.PI / 2;

    this.instSpheres.scale.set(0.055, 0.055, 0.055);

    this.scene.add(this.instSpheres);

    this.addLights();
    this.initEvents();
    this.update();
  }

  setSize(camera, plane) {
    const [width, height] = this.getViewSize(camera, plane);

    plane.scale.set(width, height, 1);
  }

  getViewSize(camera, plane) {
    const fov = THREE.Math.degToRad(camera.fov);
    const dist = camera.position.z - plane.position.z;

    const height = 2 * Math.tan(fov / 2) * dist;
    const width = height * camera.aspect;

    return [width, height];
  }

  addLights() {
    const ambientLight = new THREE.AmbientLight(0xafafaf);
    this.scene.add(ambientLight);

    const pointLight = new THREE.PointLight(0xffffff, 0.5);
    pointLight.position.set(0, 5, 5);
    this.scene.add(pointLight);
  }

  update() {
    this.renderer.setAnimationLoop(() => {
      const time = this.clock.getElapsedTime();
      if (this.resizeRendererToDisplaySize(this.renderer)) {
        const canvas = this.renderer.domElement;
        this.camera.aspect = canvas.clientWidth / canvas.clientHeight;
        this.camera.updateProjectionMatrix();
      }

      this.uniforms.time.value = time;
      this.render();
    });
  }

  resizeRendererToDisplaySize(renderer) {
    const canvas = renderer.domElement;
    const width = canvas.clientWidth;
    const height = canvas.clientHeight;
    const needResize = canvas.width !== width || canvas.height !== height;
    if (needResize) {
      //this.planeTrail.material.uniforms.resolution.value.set(width, height);
      //this.uniforms.resolution.value.set(width, height);

      renderer.setSize(width, height, false);
    }
    return needResize;
  }

  swapRenderTarget() {
    const renderA = this.rt;
    this.rt = this.rt2;
    this.rt2 = renderA;
  }

  render() {
    this.swapRenderTarget();

    this.renderer.setRenderTarget(this.rt);
    this.renderer.render(this.rtScene, this.rtCamera);

    this.planeTrail.material.uniforms.bufferTexture.value = this.rt.texture;
    this.uniforms.bufferTexture.value = this.rt2.texture;

    this.renderer.setRenderTarget(null);
    this.renderer.render(this.scene, this.camera);
  }
}

new Webgl();

              
            
!
999px

Console