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.

            
              const {
  WebGLRenderer, Scene, PerspectiveCamera, Object3D, Mesh,
  MeshToonMaterial, Color, SphereGeometry, PlaneGeometry, MeshLambertMaterial,
  Vector3, AmbientLight, PointLight, DirectionalLight, Fog,
} = THREE;

const getRandomFloat = (min, max) => (Math.random() * (max - min) + min);
const radians = degrees => degrees * Math.PI / 180;
const getNormalizedPosFromScreen = (x, y) => new Vector3(
  ((x / window.innerWidth) * 2) - 1,
  -((y / window.innerHeight) * 2) + 1,
  0.5,
);
// https://stackoverflow.com/questions/13055214/mouse-canvas-x-y-to-three-js-world-x-y-z
const getDistanceBetweenNormalizedMousePosAndPos = (normalizedMousePos, pos, camera) => {
  const nm = normalizedMousePos.clone()
  nm.unproject(camera);
  const dir = nm.sub(camera.position).normalize();
  const distance = (pos.z - camera.position.z) / dir.z;
  const mousePos = camera.position.clone().add(dir.multiplyScalar(distance));
  return pos.clone().sub(mousePos);
};



/**/ /* ---- CORE ---- */
/**/ const mainColor = '#ffffff';
/**/ const secondaryColor = '#ffffff';
/**/ const bgColor = 0xffffff;
/**/ let windowWidth = window.innerWidth;
/**/ let windowHeight = window.innerHeight;
/**/ class Webgl {
/**/   constructor(w, h) {
/**/     this.meshCount = 0;
/**/     this.meshListeners = [];
/**/     this.renderer = new WebGLRenderer({ antialias: true, alpha: true });
/**/     this.renderer.setPixelRatio(window.devicePixelRatio);
/**/     this.renderer.setClearColor(bgColor);
/**/     this.scene = new Scene(); 
/**/     this.camera = new PerspectiveCamera(40, w / h, 1, 1000);
/**/     this.camera.position.set(0, 0, 6);
/**/     this.dom = this.renderer.domElement;
/**/     this.update = this.update.bind(this);
/**/     this.resize = this.resize.bind(this);
/**/     this.resize(w, h); // set render size
/**/   }
/**/   add(mesh) {
/**/     this.scene.add(mesh);
/**/     if (!mesh.update) return;
/**/     this.meshListeners.push(mesh.update);
/**/     this.meshCount++;
/**/   }
/**/   update() {
/**/     let i = this.meshCount;
/**/     while (--i >= 0) {
/**/       this.meshListeners[i].apply(this, null);
/**/     }
/**/
/**/      this.camera.position.x += ((normalizedMouse.x * 2) - this.camera.position.x) * 0.03;
/**/			this.camera.position.y += ((normalizedMouse.y * 1.5) - this.camera.position.y) * 0.03;
/**/			this.camera.lookAt(new Vector3());
/**/
/**/     this.renderer.render(this.scene, this.camera);
/**/   }
/**/   resize(w, h) {
/**/     this.camera.aspect = w / h;
/**/     this.camera.updateProjectionMatrix();
/**/     this.renderer.setSize(w, h);
/**/   }
/**/ }
/**/ const webgl = new Webgl(windowWidth, windowHeight);
/**/ document.body.appendChild(webgl.dom);

/* ---- CREATING ZONE ---- */

const SCALE_FORCE = 0.1;
const SCALE_VEL = 0.5;

const MOUSE_VEL = 0.3;

const ATTRACTION_FORCE = 0.2;
const ATTRACTION_VEL = 0.2;

const NBR_OF_BALLS = 200;
const COLORS = [
  '#FEE4EC',
  '#EDE7F6',
  '#E0F2FF',
  '#FFF3B1',
  '#E8F5E9',
  '#DEF7FA',
];

// OBJECTS
class Ball extends Mesh {
  constructor({
    size = getRandomFloat(0.1, 0.15),
    position = new Vector3(
      getRandomFloat(-8, 8),
      getRandomFloat(-5, 5),
      getRandomFloat(-7, 2),
    ),
    color = secondaryColor,
  } = {}) {
    const material = new MeshToonMaterial({
      color: new Color(color),

    });
    const geometry = new SphereGeometry(size, 16, 16);
    super(geometry, material);

    this.normalizedMouseVec = new Vector3();
    this.attractionRadius = size * 10;
    this.force = {
      scale: 0,
      position: new Vector3(),
    };

    this.initialPosition = position;
    this.position.copy(this.initialPosition);
    this.scale.multiplyScalar(0.001);

    this.update = this.update.bind(this);
  }

  update() {
    // this.rotation.x += 0.005;
    // this.rotation.y += 0.005;

    this.updateScale();
    this.updateMouseAttractionForce();
  }

  updateScale() {
    this.force.scale += (1 - this.scale.x) * SCALE_FORCE;
    this.scale.addScalar(this.force.scale);
    this.force.scale *= SCALE_VEL;
  }

  updateMouseAttractionForce() {
    // mousePosition force
    const vecForce = getDistanceBetweenNormalizedMousePosAndPos(this.normalizedMouseVec, this.position, webgl.camera);
    const force = Math.max(0, this.attractionRadius - vecForce.length());
    this.force.position.add(vecForce.multiplyScalar(force * MOUSE_VEL));
    // dist force
    this.force.position.sub(this.initialPosition.clone().sub(this.position).multiplyScalar(ATTRACTION_FORCE))
    // apply
    this.position.sub(this.force.position);
    // reduce force
    this.force.position.multiplyScalar(ATTRACTION_VEL);
  }
}

// #######
// START
// #######

// #######

// lights
const ambiantLight = new AmbientLight(0xffffff, .95);
webgl.add(ambiantLight);

const pointLight = new PointLight(0xffffff, 1);

// #######
// balls
let j = 0;
let normalizedMouse = new Vector3();
const balls = [];

// push new balls each 20 ms
let interval = setInterval(() => {
  const b = new Ball({ color: COLORS[Math.floor(Math.random() * COLORS.length)] });
  balls.push(b);
  webgl.add(b);
  j++;

  if (j === NBR_OF_BALLS) {
    clearInterval(interval);
  }
}, 20);

// target mouse position in the 3D view
document.body.addEventListener('mousemove', (e) => {
  normalizedMouse = getNormalizedPosFromScreen(e.clientX, e.clientY)
  const l = balls.length;
  for (let i = 0; i < l; i++) {
    balls[i].normalizedMouseVec = normalizedMouse;
  }
});

/* ---- CREATING ZONE END ---- */
/**/
/**/
/**/ /* ---- ON RESIZE ---- */
/**/ function _onResize() {
/**/   windowWidth = window.innerWidth;
/**/   windowHeight = window.innerHeight;
/**/   webgl.resize(windowWidth, windowHeight);
/**/ }
/**/ window.addEventListener('resize', _onResize);
/**/ window.addEventListener('orientationchange', _onResize);
/**/ /* ---- LOOP ---- */
/**/ function _loop() {
/**/ 	webgl.update();
/**/ 	requestAnimationFrame(_loop);
/**/ }
/**/ _loop();

            
          
!
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