As a newcomer to Three.js, I embarked on an experiment where I created multiple spheres and attempted to give them a "hover" effect. Essentially, when the mouse hovers over a sphere, it enlarges, and when the mouse moves away, it shrinks back to its original size.
This is what I came up with:
// Initializing the Scene, Camera, and Renderer
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 10;
var renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setClearColor("#F4F4F4");
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Event listeners for window resize
window.addEventListener('resize', () => {
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
});
// Orbit Controls setup
controls = new THREE.OrbitControls(camera, renderer.domELement);
// Raycaster for mouse interactions
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
// Creating Multiple Spheres
var geometry = new THREE.SphereGeometry(1, 10, 10);
var material = new THREE.MeshNormalMaterial({ wireframe: true });
var meshX = -10;
for (var i = 0; i < 15; i++) {
var mesh = new THREE.Mesh(geometry, material);
mesh.position.x = (Math.random() - 0.5) * 10;
mesh.position.y = (Math.random() - 0.5) * 10;
mesh.position.z = (Math.random() - 0.5) * 10;
scene.add(mesh);
meshX += 1;
}
// Adding Light source
var light = new THREE.PointLight(0xFFFFFF, 1, 500)
light.position.set(10, 0, 25);
scene.add(light);
// Render function for animation
var render = function() {
requestAnimationFrame(render);
renderer.render(scene, camera);
}
// Interaction animations on mouse move and leave
function onMouseMove(event) {
// Implementation omitted for brevity
}
function onMouseLeave(event) {
// Implementation omitted for brevity
}
// Event Listeners for mouse movements
window.addEventListener('mousemove', onMouseMove);
window.addEventListener('mouseleave', onMouseLeave);
render();
I encountered some issues with this approach, particularly around defining the animation for "mouseleave." To work around this, I explored using THREEx.domevents.js, but ran into limitations in applying the hover effect to all spheres rather than just one. Here's a preview of the behavior and code snippet: GIF Preview of THREEx.domevents.js impact
// Further implementation using THREEx.domevents.js for interaction events
// Detailed explanation included within the provided link
// Any help or guidance on resolving these challenges would be greatly appreciated. Thank you!