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.

            
              <div id="content-canvas"></div>

            
          
!
            
              body{
  margin: 0;
  display: flex;
}

#content-canvas{
  width: 100%;
  height: 100vh;
}

canvas{
  width: 100%;
  height: 100%;
  display: block;
}
            
          
!
            
              const s = {
  vs: `
      #define NUM_OCTAVES 8

      uniform vec3 mouse;
      uniform float time;

      varying vec2 vUv;

      float random(vec2 st) {
          return fract(sin(dot(st.xy,
                               vec2(12.9898,78.233)))*
              43758.5453123);
      }

      void main(){
        vec3 newpos = position;
        vec3 dir = newpos - mouse;
        float dist = length(dir);
        float radius = 5.;

        float ratio = 1. - clamp(dist / radius, 0.0, 1.0);
        vec3 pos = dir * 3. * random(ratio + uv);
        newpos += mix(vec3(0.), pos, vec3(ratio));

        vec4 mvPosition = modelViewMatrix * vec4(newpos, 1.0);
        gl_PointSize = 100. * (1. / - mvPosition.z);
        gl_Position = projectionMatrix * mvPosition;

        vUv = uv;
      }
`,
  fs: `
      varying vec2 vUv;

      void main(){ 
        vec2 uv = vUv;
        
        if (length(gl_PointCoord.xy - vec2(0.5)) > 0.5) discard;

        vec3 color = vec3(0, 255, 255) / 255.;
        gl_FragColor = vec4(color, 1.);
      }
`
};

// Carga modelos 3D externos o texturas dependiendo de la opcion
const loaderFiles = {
  gltf: new THREE.GLTFLoader(),
  texture: new THREE.TextureLoader()
};

class WebGL {
  constructor() {
    this.renderer = new THREE.WebGLRenderer({ antialias: true });
    this.camera = new THREE.PerspectiveCamera(
      45,
      innerWidth / innerHeight,
      0.1,
      1000
    );
    this.scene = new THREE.Scene();
    this.group = new THREE.Group();
    this.clock = new THREE.Clock();
    this.raycaster = new THREE.Raycaster();
    this.mouse = new THREE.Vector3();

    this.helper = new Helper(this.scene);
    this.loader = loaderFiles.gltf;
  }

  // Coloca el objeto renderer dentro del DOM
  // Instaciamos la clase OrbitControls para mover la camara
  // Agrega la camara y el objeto group dentro de la escena
  init() {
    this.scene.add(this.camera);
    this.scene.add(this.group);

    this.scene.background = new THREE.Color(0x1d1e22);

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

    this.camera.position.set(0, 10, 50);
    this.camera.lookAt(this.scene.position);

    //this.helper.axes(100);

    const _contentCanvas = document.querySelector("#content-canvas");
    _contentCanvas.appendChild(this.renderer.domElement);

    this.loadModel();

    window.addEventListener("resize", this.onResize);
    window.addEventListener("mousemove", ev => this.onMousemove(ev));
  }

  // Inicia todos los metodos que serviran para crear nuestro espacio y objetos
  loadModel() {
    this.loader.load(
      "https://rawcdn.githack.com/AlainBarrios/3d-models/694ea0751aab59c235390f61e81ee1d37f328d5a/knight_girl.glb?raw=true",
      gltf => {
        this.uniforms = {
          time: {
            type: "f",
            value: 0
          },
          resolution: {
            type: "v2",
            value: new THREE.Vector2(innerWidth, innerHeight)
          },
          mouse: {
            type: "v3",
            value: new THREE.Vector3(0, 0, 0)
          }
        };

        const mat = new THREE.ShaderMaterial({
          uniforms: this.uniforms,
          vertexShader: s.vs,
          fragmentShader: s.fs
        });

        const positions = this.combineBuffer(gltf, "position");

        const geo = new THREE.BufferGeometry();
        geo.addAttribute("position", positions);

        geo.computeBoundingBox();
        geo.attributes.position.setDynamic(true);
        geo.rotateX(-Math.PI * 0.5);

        this._modelMesh = new THREE.Points(geo, mat);
        this._modelMesh.position.set(0, -10, 0);
        this.scene.add(this._modelMesh);

        this.plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);

        this.endAnimation();
        this.animate();
        this.addLight();
      },

      xhr => {
        console.log(xhr.loaded / xhr.total * 100 + "% loaded");
      },

      error => {
        console.log("An error happened");
      }
    );
  }

  endAnimation() {
    this.controls.addEventListener("end", () => {
      this.plane.normal.copy(this.camera.position);
      this.plane.normal.y = 0;
      this.plane.normal.normalize();
    });
  }

  combineBuffer(model, bufferName) {
    let count = 0;

    model.scene.traverse(child => {
      if (child.isMesh) {
        const buffer = child.geometry.attributes[bufferName];
        count += buffer.array.length;
      }
    });

    const combined = new Float32Array(count);

    let offset = 0;

    model.scene.traverse(child => {
      if (child.isMesh) {
        const buffer = child.geometry.attributes[bufferName];
        combined.set(buffer.array, offset);
        offset += buffer.array.length;
      }
    });

    return new THREE.BufferAttribute(combined, 3);
  }

  addLight() {
    const ambientLight = new THREE.HemisphereLight(
      0xddeeff, // sky color
      0x202020, // ground color
      5 // intensity
    );

    this.scene.add(ambientLight);

    const mainLight = new THREE.DirectionalLight(0xffffff, 3);
    mainLight.position.set(10, 10, 10);

    this.scene.add(mainLight);
  }

  onMousemove(ev) {
    this.mouse.x = ev.clientX / innerWidth * 2 - 1;
    this.mouse.y = -(ev.clientY / innerHeight) * 2 + 1;

    this.raycaster.setFromCamera(this.mouse, this.camera);

    this.raycaster.ray.intersectPlane(this.plane, this.uniforms.mouse.value);
    this._modelMesh.worldToLocal(this.uniforms.mouse.value);
  }

  // Actualiza cualquier cambio, para luego representarlo en el canvas
  animate() {
    const that = this;
    this.renderer.setAnimationLoop(() => {
      const time = this.clock.getElapsedTime() * 0.5;

      this._modelMesh.rotation.y = time * 0.5;
      this.uniforms.time.value = time;

      if (that.resizeRendererToDisplaySize(that.renderer)) {
        const canvas = that.renderer.domElement;
        that.camera.aspect = canvas.clientWidth / canvas.clientHeight;
        that.camera.updateProjectionMatrix();
      }

      this.render();
    });
  }

  // Rescala el canvas y escenario
  resizeRendererToDisplaySize(renderer) {
    const canvas = renderer.domElement;
    const width = canvas.clientWidth;
    const height = canvas.clientHeight;
    const needResize = canvas.width !== width || canvas.height !== height;
    if (needResize) {
      renderer.setSize(width, height, false);
    }
    return needResize;
  }

  // Renderiza nuestro escenario
  render() {
    this.renderer.render(this.scene, this.camera);
  }
}

const webgl = new WebGL();
webgl.init();

            
          
!
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.

Console