// Animation loop
function animate() {
controls.update();
renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);
"add levitating effect on globe "
To add a levitating effect for the globe, we can create a smooth up-and-down animation of the position of the globe in the animate function. Additionally, we can use a sine wave to ensure that the animation is smooth and perpetual.
Here's the modification needed to implement the levitating effect:
Changes in Code:
Add a clock to manage time for the levitation animation.
Use a sine wave to change the vertical position (y) of the globe.
Update the animate loop to include the levitation movement.
Here is your updated code with levitation added:
javascript
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
// Antialiasing and responsiveness
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);
// Orbit Controls for better interaction
const controls = new OrbitControls(camera, renderer.domElement);
controls.autoRotate = true; // Enable auto-rotate initially
controls.enableDamping = true;
// Camera initial position
camera.position.set(0, 0, 10);
controls.update();
// Create Globe geometry
const globeGeometry = new THREE.SphereGeometry(5, 180, 90);
// Load map texture (earth texture)
const textureLoader = new THREE.TextureLoader();
const earthTexture = textureLoader.load("/map.jpg");
const pointTexture = textureLoader.load("/circle.png"); // Particle shape texture
// Material for the Points (using ShaderMaterial)
const globeMaterial = new THREE.ShaderMaterial({
uniforms: {
visibilityTexture: { value: earthTexture }, // Earth texture map
pointTexture: { value: pointTexture }, // Particle circular texture
pointSize: { value: 0.1 }, // Size of particles
scale: { value: window.innerHeight / 2 }, // Scale relative to screen
},
vertexShader: `
uniform float scale;
uniform float pointSize;
varying vec2 vUv; // Pass UVs to fragment shader for texture lookup
void main() {
vUv = uv; // Pass uv coordinates to fragment shader
vec4 mvPosition = modelViewMatrix * vec4(position, 1.0); // Transform vertex
gl_PointSize = pointSize * (scale / length(mvPosition.xyz)); // Set size of particles
gl_Position = projectionMatrix * mvPosition; // Final position
}
`,
fragmentShader: `
uniform sampler2D visibilityTexture; // Texture for visibility
uniform sampler2D pointTexture; // Shape of the particles
varying vec2 vUv;
void main() {
// Sample from the visibility texture (earth texture)
vec4 visibility = texture2D(visibilityTexture, vUv);
// Discard invisible pixels (based on earth texture brightness)
if (visibility.r < 0.1) discard;
// Sample the particle shape texture
vec4 shape = texture2D(pointTexture, gl_PointCoord);
// Discard based on alpha channel of shape
if (shape.a < 0.1) discard;
// Final color
gl_FragColor = vec4(visibility.rgb, 1.0) * shape;
}
`,
transparent: true,
});
// Create particle-based globe using Points
const globePoints = new THREE.Points(globeGeometry, globeMaterial);
// Group to apply levitation animation
const globeGroup = new THREE.Group();
globeGroup.add(globePoints);
scene.add(globeGroup);
// Create an invisible globe (for hover detection)
const globeBasicMaterial = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0, // Fully invisible
});
const globe = new THREE.Mesh(globeGeometry, globeBasicMaterial);
globeGroup.add(globe);
// Raycaster for mouse interaction
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
let isHovering = false;
// Event listeners for mouse movement
const onMouseMove = (event) => {
// Calculate mouse position in normalized device coordinates (-1 to +1)
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
// Update the raycaster
raycaster.setFromCamera(mouse, camera);
// Check for intersection with the invisible globe
const intersects = raycaster.intersectObject(globe);
if (intersects.length > 0) {
// Mouse is hovering over the globe
if (!isHovering) {
isHovering = true;
controls.autoRotate = false; // Disable auto-rotate
}
} else {
// Mouse is not hovering over the globe
if (isHovering) {
isHovering = false;
controls.autoRotate = true; // Re-enable auto-rotate
}
}
};
window.addEventListener("mousemove", onMouseMove);
// Responsive resizing
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// Clock for animation
const clock = new THREE.Clock();
// Animation loop
function animate() {
// Get elapsed time
const elapsedTime = clock.getElapsedTime();
// Smooth levitation using a sine wave
const levitationHeight = 0.2; // Adjust for how high it levitates
globeGroup.position.y = Math.sin(elapsedTime * 2) * levitationHeight;
// Update Orbit Controls
controls.update();
// Render the Scene
renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);
Explanation of Changes:
Levitation Animation:
The globeGroup is a THREE.Group that contains the globe (both visible globePoints and invisible globe for interactions). By animating its position.y, we achieve a levitating effect.
Using Math.sin(elapsedTime * 2) creates a smooth oscillation along the vertical axis.
Clock:
Used to track the elapsed time. This ensures the animation is smooth and time-uniform.
Levitation Height:
Controlled using the levitationHeight variable — you can tweak this to adjust the height of the levitation effect.
Visual Effect:
The globe will now smoothly float up and down while also rotating (if auto-rotate is enabled). The levitation effect will be smooth and continuous.
To add markers on the globe, which display text on hover, we can follow these steps:
Create markers:
Use THREE.Sprite or simple THREE.Mesh geometries such as spheres or planes to represent the markers.
Position markers:
Place them on the surface of the globe using latitude and longitude coordinates converted to 3D positions on a sphere.
Hover interaction:
Use the Raycaster to detect when the mouse is hovering over a marker.
When hovering over a marker, display corresponding text in the scene (e.g., using a DOM element or THREE.Sprite for 3D text).
Here’s the updated code implementing the above steps:
Changes to the Code:
Below is the modified code where markers are added:
javascript
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
// Renderer
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);
// Orbit Controls
const controls = new OrbitControls(camera, renderer.domElement);
controls.autoRotate = true;
controls.enableDamping = true;
// Camera position
camera.position.set(0, 0, 10);
controls.update();
// Create Globe
const globeGeometry = new THREE.SphereGeometry(5, 180, 90);
const textureLoader = new THREE.TextureLoader();
const earthTexture = textureLoader.load("/map.jpg");
const globeMaterial = new THREE.MeshBasicMaterial({ map: earthTexture });
const globe = new THREE.Mesh(globeGeometry, globeMaterial);
scene.add(globe);
// Group for globe and markers
const globeGroup = new THREE.Group();
globeGroup.add(globe);
scene.add(globeGroup);
// Clock for animation
const clock = new THREE.Clock();
// Create markers using PlaneGeometry or Sprite
const markers = [];
const markerData = [
{ lat: 37.7749, lon: -122.4194, label: "San Francisco" },
{ lat: 48.8566, lon: 2.3522, label: "Paris" },
{ lat: 35.6762, lon: 139.6503, label: "Tokyo" },
{ lat: -33.8688, lon: 151.2093, label: "Sydney" },
];
// Function to convert lat/lon to 3D position on sphere
function latLonToVector3(lat, lon, radius = 5) {
const phi = (90 - lat) * (Math.PI / 180); // Convert latitude to radians
const theta = (lon + 180) * (Math.PI / 180); // Convert longitude to radians
const x = -(radius * Math.sin(phi) * Math.cos(theta));
const y = radius * Math.cos(phi);
const z = radius * Math.sin(phi) * Math.sin(theta);
return new THREE.Vector3(x, y, z);
}
// Add markers to the globe
markerData.forEach((data) => {
const markerGeometry = new THREE.SphereGeometry(0.1, 16, 16);
const markerMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
const marker = new THREE.Mesh(markerGeometry, markerMaterial);
// Position marker using lat/lon
const position = latLonToVector3(data.lat, data.lon);
marker.position.copy(position);
// Store label data in marker's userData
marker.userData.label = data.label;
// Face the marker outward (towards the outside of the sphere)
marker.lookAt(marker.position.clone().normalize().multiplyScalar(10));
globeGroup.add(marker);
markers.push(marker);
});
// Raycaster for hover interactions
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
// Create a DOM element for displaying text on hover
const hoverLabel = document.createElement("div");
hoverLabel.style.position = "absolute";
hoverLabel.style.padding = "8px";
hoverLabel.style.background = "rgba(0, 0, 0, 0.5)";
hoverLabel.style.color = "#fff";
hoverLabel.style.borderRadius = "4px";
hoverLabel.style.display = "none";
document.body.appendChild(hoverLabel);
// Event listener for mouse move
function onMouseMove(event) {
// Calculate mouse position in normalized device coordinates (-1 to 1)
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
// Update raycaster with mouse position and camera
raycaster.setFromCamera(mouse, camera);
// Find intersections with markers
const intersects = raycaster.intersectObjects(markers);
if (intersects.length > 0) {
const marker = intersects[0].object;
// Display hover label with the marker's label
hoverLabel.style.display = "block";
hoverLabel.style.left = `${event.clientX}px`;
hoverLabel.style.top = `${event.clientY}px`;
hoverLabel.textContent = marker.userData.label;
controls.autoRotate = false; // Disable autorotate when hovering
} else {
hoverLabel.style.display = "none";
controls.autoRotate = true; // Re-enable autorotate when not hovering
}
}
window.addEventListener("mousemove", onMouseMove);
// Responsive resizing
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// Animation loop
function animate() {
const elapsedTime = clock.getElapsedTime();
// Levitating effect for the globe
const levitationHeight = 0.2;
globeGroup.position.y = Math.sin(elapsedTime * 2) * levitationHeight;
// Update Orbit Controls
controls.update();
// Render the scene
renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);
Explanation of New Features:
1. Adding Markers:
Markers are added to represent locations. They are created using THREE.SphereGeometry and positioned on the globe using the latLonToVector3 function, which converts latitude and longitude into 3D positions.
2. Hover Detection:
Raycaster detects when the mouse is hovering over a marker.
If a marker is hovered over, its label (stored in userData) is displayed using a styled HTML div.
3. Label Display:
A hoverLabel DOM element is dynamically positioned near the mouse cursor and updated to display the current marker's label.
4. Responsive Resizing:
The globe and markers remain responsive to screen resizing.
Interactive Features:
Levitating Globe: The globe continues to levitate smoothly.
Hover-over Markers: Moving the mouse over a marker displays a label showing the marker's corresponding location name.
Auto-Rotate Toggle: Auto-rotation pauses when the user hovers over a marker and resumes when the mouse moves away.
Visual Effect:
You’ll see a revolving and levitating globe with red markers indicating specific locations. Hovering over the markers will show the corresponding text labels near the mouse cursor!
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
// Antialiasing and responsiveness
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);
// Function to convert lat/lon to 3D position on sphere
function latLonToVector3(lat, lon, radius = 5) {
const phi = (90 - lat) * (Math.PI / 180); // Convert latitude to radians
const theta = (lon + 180) * (Math.PI / 180); // Convert longitude to radians
const x = -(radius * Math.sin(phi) * Math.cos(theta));
const y = radius * Math.cos(phi);
const z = radius * Math.sin(phi) * Math.sin(theta);
return new THREE.Vector3(x, y, z);
}
// Add markers to the globe
markerData.forEach((data) => {
const markerGeometry = new THREE.SphereGeometry(0.1, 16, 16);
const markerMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
const marker = new THREE.Mesh(markerGeometry, markerMaterial);
// Position marker using lat/lon
const position = latLonToVector3(data.lat, data.lon);
marker.position.copy(position);
// Store label data in marker's userData
marker.userData.label = data.label;
// Face the marker outward (towards the outside of the sphere)
marker.lookAt(marker.position.clone().normalize().multiplyScalar(10));
globeGroup.add(marker);
markers.push(marker);
});
// Raycaster for mouse interaction
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
let isHovering = false;
// Create a DOM element for displaying text on hover
const hoverLabel = document.createElement("div");
hoverLabel.style.position = "absolute";
hoverLabel.style.padding = "8px";
hoverLabel.style.background = "rgba(0, 0, 0, 0.5)";
hoverLabel.style.color = "#fff";
hoverLabel.style.borderRadius = "4px";
hoverLabel.style.display = "none";
document.body.appendChild(hoverLabel);
// Event listeners for mouse movement
const onMouseMove = (event) => {
// Calculate mouse position in normalized device coordinates (-1 to +1)
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
// Update the raycaster
raycaster.setFromCamera(mouse, camera);
// Check for intersection with the invisible globe
const intersects = raycaster.intersectObject(globe);
const intersectsMarkers = raycaster.intersectObjects(markers);
if (intersects.length > 0) {
// Mouse is hovering over the globe
if (!isHovering) {
isHovering = true;
controls.autoRotate = false; // Disable auto-rotate
}
} else {
// Mouse is not hovering over the globe
if (isHovering) {
isHovering = false;
controls.autoRotate = true; // Re-enable auto-rotate
}
}
if (intersectsMarkers.length > 0) {
const marker = intersects[0].object;
code
// Display hover label with the marker's label
hoverLabel.style.display = "block";
hoverLabel.style.left = `${event.clientX}px`;
hoverLabel.style.top = `${event.clientY}px`;
hoverLabel.textContent = marker.userData.label;
// Clock for animation
const clock = new THREE.Clock();
// Animation loop
function animate() {
// Get elapsed time
const elapsedTime = clock.getElapsedTime();
// Smooth levitation using a sine wave
const levitationHeight = 0.2; // Adjust for how high it levitates
globeGroup.position.y = Math.sin(elapsedTime * 2) * levitationHeight;
// Update Orbit Controls
controls.update();
// Render the Scene
renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);
"look this i do some mistake beacause on hover not show text but show black box with opacity"
It seems the issue lies in the way the Raycaster is used to detect markers. Specifically, in the following portion of your code:
javascript
const marker = intersects[0].object;
This line should actually reference the intersectsMarkers array (which contains the intersections with the markers), but you are mistakenly referencing intersects, which relates to the invisible globe instead.
Let's fix this issue!
Correct Hover Logic:
Replace this block of code inside the onMouseMove function:
javascript
if (intersectsMarkers.length > 0) {
const marker = intersects[0].object; // <-- WRONG: should reference intersectsMarkers, not intersects
// Display hover label with the marker's label
hoverLabel.style.display = "block";
hoverLabel.style.left = `${event.clientX}px`;
hoverLabel.style.top = `${event.clientY}px`;
hoverLabel.textContent = marker.userData.label;
} else {
hoverLabel.style.display = "none";
}
With this corrected block:
javascript
if (intersectsMarkers.length > 0) {
const marker = intersectsMarkers[0].object; // <-- Fix: Now referencing the correct array
// Display hover label with the marker's label
hoverLabel.style.display = "block";
hoverLabel.style.left = `${event.clientX + 10}px`; // Adjust position to avoid mouse overlapping
hoverLabel.style.top = `${event.clientY + 10}px`;
hoverLabel.textContent = marker.userData.label; // Get the label from userData
} else {
hoverLabel.style.display = "none";
}
Explanation of Fix:
Switch from intersects to intersectsMarkers:
intersects checks for intersection with the invisible globe, not the markers.
You need to test intersectsMarkers, which contains the intersected objects from the markers array.
Correctly Access the Marker Object:
Access the object in intersectsMarkers[0] to retrieve the correct marker.
DOM Position Adjustment:
Adjust the label position slightly (+10 pixels) to avoid the mouse cursor overlapping the label.
Full Corrected Code for onMouseMove:
Here’s the full working onMouseMove function with the fix applied:
javascript
const onMouseMove = (event) => {
// Calculate mouse position in normalized device coordinates (-1 to +1)
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
// Update the raycaster
raycaster.setFromCamera(mouse, camera);
// Check for intersection with the invisible globe
const intersects = raycaster.intersectObject(globe);
const intersectsMarkers = raycaster.intersectObjects(markers);
if (intersects.length > 0) {
// Mouse is hovering over the globe
if (!isHovering) {
isHovering = true;
controls.autoRotate = false; // Disable auto-rotate
}
} else {
// Mouse is not hovering over the globe
if (isHovering) {
isHovering = false;
controls.autoRotate = true; // Re-enable auto-rotate
}
}
// Hover interaction for markers
if (intersectsMarkers.length > 0) {
const marker = intersectsMarkers[0].object; // FIX: Reference markers intersection array
// Display hover label with the marker's label
hoverLabel.style.display = "block";
hoverLabel.style.left = `${event.clientX + 10}px`; // Adjust to avoid overlapping with cursor
hoverLabel.style.top = `${event.clientY + 10}px`;
hoverLabel.textContent = marker.userData.label; // Set text content from marker's label
} else {
hoverLabel.style.display = "none";
}
};
Additional Notes:
Opacity Issue: The "black box with opacity" issue arises because the hoverLabel text is either empty (textContent isn't properly set) or the wrong marker logic is being used. The fix ensures the label updates correctly with the appropriate text.
Positioning the Label: Adjusted the hover label's position slightly (+10px) so it doesn’t overlap with the mouse cursor for better user experience.
Now, your marker labels should display correctly when you hover over each marker! 🎉