show me the documentation and a working example of how arcs and their dash animation can be added to a three js three-globe in react
Assistant
Creating an animated dash effect for arcs in a three.js globe using React involves working with three.js's materials and geometries, as well as integrating it into your React application. To achieve this, you'll also want to make use of the react-three-fiber (R3F) library which is a React renderer for three.js.
First, let's focus on setting up a basic three-globe using react-three-fiber, and then we'll proceed to add arcs with dash animation.
Here's a step-by-step guide to create the animated arcs on a globe within a React application. It assumes you have already set up a React project using Create React App and have installed the necessary dependencies.
Install the necessary packages:
bash
npm install three @react-three/fiber react-three-globe
Create the ThreeGlobe component:
In your React component, you need to set up a three-globe and create a custom component to handle the arcs and their animation.
jsx
// ThreeGlobe.jsx
import React, { useRef, useEffect } from 'react';
import { Canvas, useFrame } from '@react-three/fiber';
import { Sphere, Line } from '@react-three/drei';
import * as THREE from 'three';
function AnimatedArc({ start, end, color }) {
// The arc geometry will be generated between two points
const geomRef = useRef();
const arcRef = useRef();
useEffect(() => {
// Create an arc curve between start and end points
const startVec = new THREE.Vector3(...start);
const endVec = new THREE.Vector3(...end);
const curve = new THREE.Curve();
curve.getPoint = t => {
const vec = startVec.clone().lerp(endVec, t);
vec.normalize().multiplyScalar(1 + 0.1 * Math.sin(Math.PI * t)); // elevate the arc
return vec;
};
const points = curve.getPoints(50);
geomRef.current.setFromPoints(points);
// Initialize the dash with the line length
const line = new THREE.Line(geomRef.current);
const lineLength = line.computeLineDistances().lineDistances[1];
arcRef.current.material.dashSize = lineLength;
arcRef.current.material.gapSize = lineLength;
}, [start, end]);
useFrame(() => {
if (arcRef.current) {
// Update the dash offset to create the animation effect
arcRef.current.material.dashOffset -= 0.02;
}
});
return (
<Line
ref={arcRef}
geometry={geomRef.current}
points={[]}
color={color}
lineWidth={2}
dashed={true}
/>
);
}
function ThreeGlobe() {
return (
<Canvas>
<ambientLight intensity={0.5} />
<pointLight position={[10, 10, 10]} />
// Add a simple sphere to represent the Earth
<Sphere args={[1, 64, 64]}>
<meshPhongMaterial attach="material" color="royalblue" />
</Sphere>
<AnimatedArc start={[0, 0, 1]} end={[0.5, 0.5, 0.5]} color="white" />
</Canvas>
);
}
export default ThreeGlobe;
Use the ThreeGlobe component:
Now, in your App.js (or any React component), you can import and use the ThreeGlobe component.
jsx
// App.js
import React from 'react';
import './App.css';
import ThreeGlobe from './ThreeGlobe';
function App() {
return (
<div className="App">
<header className="App-header">
<ThreeGlobe />
</header>
</div>
);
}
export default App;
Run your application:
Make sure your React application is running, and you should see a globe with an animated dash arc.
This is a simple example of how to create animated dashed arcs on a 3D globe using React and react-three-fiber. You might need to adjust positions, color, and other properties as per your requirements. Additionally, the performance and exact visuals can be fine-tuned by altering the code for creating the arc curve and the animation loop within useFrame. Remember to ensure that react-three-fiber and three are compatible with the versions you install and use in your projects.
User
whats the difference between three-globe and react-three-globe
Assistant
three-globe and react-three-globe are both libraries that facilitate the creation of 3D globes, and they have similar goals but are designed for different environments.
three-globe:
three-globe is a JavaScript library that is used in conjunction with three.js, which is a 3D library that creates and displays animated 3D computer graphics in a web browser using WebGL.
It is not specifically tailored for React and can be used with plain JavaScript or any JavaScript framework.
When using three-globe in a React application, you would typically need to manage three.js object lifecycles and hooks manually, creating and disposing of objects to prevent memory leaks.
react-three-globe:
react-three-globe is a React component that wraps around three-globe, providing an easier and more React-friendly way to integrate a 3D globe into React applications.
It integrates with React’s component lifecycle and lets you use the globe as a React component, which simplifies state management and reactivity.
react-three-globe is ideal for React developers who want to handle 3D globe visualizations using React's declarative programming style and state management capabilities.
In essence, if you're working within a React application, react-three-globe will typically offer a smoother and more integrated experience, as it will leverage React's component model and state management system. On the other hand, if you're not using React or you need more direct and low-level access to the three.js implementation, you may opt to use three-globe.
User
refactor my code to use react-three-globe instead of three-globe: import React, { useEffect, useRef } from 'react';
import {
WebGLRenderer,
Scene,
AmbientLight,
DirectionalLight,
Color,
Fog,
PerspectiveCamera,
PointLight
} from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { createGlowMesh } from 'three-glow-mesh';
import ThreeGlobe from "three-globe";
import countries from './files/globe-data-min.json';
import travelHistory from './files/my-flights.json';
import airportHistory from './files/my-airports.json';
let mouseX = 0;
let mouseY = 0;
let timeoutId;
let renderer, camera, scene, controls;
let Globe;
let frameId;
To refactor GlobeComponent to use react-three-globe instead of three-globe, it's important to understand that react-three-globe is a React component and should be treated as such. With react-three-fiber, you no longer need to manually create and append DOM elements for the renderer or manually handle the animation loop. Instead, you declare your scene declaratively, and react-three-fiber takes care of rendering and the animation loop behind the scenes.
The refactored version of the GlobeComponent can look something like this:
jsx
import React, { Suspense } from 'react';
import { Canvas } from '@react-three/fiber';
import { OrbitControls, PerspectiveCamera } from '@react-three/drei';
import { ReactGlobe } from 'react-three-globe';
import countries from './files/globe-data-min.json';
import travelHistory from './files/my-flights.json';
import airportHistory from './files/my-airports.json';
const GlobeComponent = ({ globeWidth, globeHeight }) => {
// Create arrays for arcs and points based on your data
// Process countries, travelHistory, and airportHistory as needed for the globe visualization
return (
<Canvas
style={{ width: globeWidth, height: globeHeight, background: 'transparent' }}
camera={{ position: [0, 0, 400] }}
>
<Suspense fallback={null}>
<ambientLight intensity={0.4} />
<directionalLight position={[-800, 2000, 400]} intensity={0.8} />
<directionalLight position={[-200, 500, 200]} intensity={1} color={0x7982f6} />
<pointLight position={[-200, 500, 200]} intensity={0.5} color={0x8566cc} />
<PerspectiveCamera makeDefault aspect={globeWidth / globeHeight} />
<ReactGlobe
hexPolygonsData={countries.features}
hexPolygonResolution={3}
hexPolygonMargin={0.7}
atmosphereColor="#ffffff"
atmosphereAltitude={0.1}
// ... other props based on your data processing
/>
<OrbitControls
enableDamping
dampingFactor={0.01}
enablePan={false}
minDistance={Math.min(globeWidth, globeHeight) / 2}
maxDistance={Math.min(globeWidth, globeHeight) / 2}
rotateSpeed={0.8}
zoomSpeed={1}
minPolarAngle={Math.PI / 3.5}
maxPolarAngle={Math.PI - Math.PI / 3}
// You may need to adjust or remove autoRotate depending on animation needs
/>
</Suspense>
</Canvas>
);
};
export default GlobeComponent;
User
give me a thorough implementation instead of a significantly simplified one since you have the code below which works. import React, { useEffect, useRef } from 'react';
import {
WebGLRenderer,
Scene,
AmbientLight,
DirectionalLight,
Color,
Fog,
PerspectiveCamera,
PointLight
} from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { createGlowMesh } from 'three-glow-mesh';
import ThreeGlobe from "three-globe";
import countries from './files/globe-data-min.json';
import travelHistory from './files/my-flights.json';
import airportHistory from './files/my-airports.json';
let mouseX = 0;
let mouseY = 0;
let timeoutId;
let renderer, camera, scene, controls;
let Globe;
let frameId;
In the following implementation, we'll refactor the existing GlobeComponent to use react-three-fiber for rendering the Three.js scene and react-three-globe for the globe component within a React application. This approach allows us to use React's component lifecycle and JSX syntax for three.js objects.
Please note that some of the dependencies like createGlowMesh and some other custom logic related to three-globe might not directly port over to react-three-globe. If functionalities like createGlowMesh are critical to your application, additional steps may be required to incorporate them into the react-three-fiber ecosystem, or you might have to create custom components for those. For the sake of this example, we'll focus on the globe and its features related to data visualization (country polygons, arcs, and points).
Here's a thorough implementation using react-three-fiber and react-three-globe:
jsx
User
fill in this implementation with my data: import React, { useRef } from 'react';
import Globe from 'react-three-globe';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { PerspectiveCamera } from 'three';
import { extend, useThree, useFrame } from '@react-three/fiber';
import countries from './files/globe-data-min.json';
import travelHistory from './files/my-flights.json';
import airportHistory from './files/my-airports.json';
// Extend will make OrbitControls available as a JSX element called orbitControls for use within the canvas
extend({ OrbitControls });
const CameraControls = () => {
// Get a reference to the Three.js Camera, and the canvas html element.
// We need these to setup the OrbitControls component.
const {
camera,
gl: { domElement },
} = useThree();
code
// Ref to the controls, so that we can update them on every frame using useFrame
const controlsRef = useRef();
useFrame(() => controlsRef.current && controlsRef.current.update());
return <orbitControls ref={controlsRef} args={[camera, domElement]} enableDamping dynamicDampingFactor={0.01} />;
It looks like you have already extracted most of the configuration into separate functions, which is great. I'll integrate those functions along with the data into the Globe component from react-three-globe.
Here's how you can use your data with the props provided by the Globe component within a react-three-fiber Canvas:
I apologize for the confusion in the previous message. The OrbitControlsImpl seems to have been mistakenly mentioned without a proper use case or import in the provided example. It appears to be a leftover from combining different parts of code and should be disregarded.
In the provided implementation, OrbitControls were imported from three/examples/jsm/controls/OrbitControls.js to be used with react-three-fiber. The extend function is used to make these controls available as a JSX component <orbitControls> within the <Canvas> provided by @react-three/fiber. The actual usage is then exemplified through the CameraControls component, which utilizes the imported and extended OrbitControls.
To correct and clarify the implementation, you should use OrbitControls as provided by @react-three/drei if you have it installed, which simplifies the usage of OrbitControls within react-three-fiber without needing to extend it. If you don't have @react-three/drei installed and wish to solely rely on three/examples/jsm/controls/OrbitControls, you would extend and use it as previously shown.
Here's an example where we don't need OrbitControlsImpl at all:
jsx
import React, { Suspense, useRef } from 'react';
import { Canvas, useThree, useFrame, extend } from '@react-three/fiber';
import { PerspectiveCamera } from '@react-three/drei';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import Globe from 'react-three-globe';
import countries from './files/globe-data-min.json';
import travelHistory from './files/my-flights.json';
import airportHistory from './files/my-airports.json';
// Make OrbitControls available as a JSX element called 'orbitControls'
extend({ OrbitControls });
const CameraControls = () => {
const { camera, gl: { domElement } } = useThree();
const orbitRef = useRef();
useFrame(() => orbitRef.current.update());
return (
<orbitControls
ref={orbitRef}
args={[camera, domElement]}
enableDamping
dynamicDampingFactor={0.01}
// ...other props you might want to pass to orbitControls
/>
);
};
// ... Rest of the GlobeComponent remains the same...
User
Unhandled Runtime Error
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of GlobeComponent.
Assistant
The error message you received indicates that you are trying to use a component that is undefined or not correctly imported.
It is possible that the error comes from incorrect imports or usage of the Globe component or orbitControls. To ensure that you don't run into such issues, please follow these steps:
Verify that you have the correct version of react-three-globe installed in your project. You can run npm install react-three-globe or yarn add react-three-globe depending on your package manager to make sure it is installed.
Import and use Globe and OrbitControls correctly in your GlobeComponent. For OrbitControls, you can use @react-three/drei which provides the controls as React components compatible with react-three-fiber. Install @react-three/drei if it's not already by running npm install @react-three/drei or yarn add @react-three/drei.
Here is an updated version of your GlobeComponent:
jsx
import React, { Suspense, useRef } from 'react';
import { Canvas, useThree, useFrame } from '@react-three/fiber';
import { OrbitControls } from '@react-three/drei';
import Globe from 'react-three-globe';
import countries from './files/globe-data-min.json';
import travelHistory from './files/my-flights.json';
import airportHistory from './files/my-airports.json';
const CameraControls = () => {
// Get access to the default camera and the gl (canvas) from the current three.js context
const {
camera,
gl: { domElement },
} = useThree();
// Update the orbit controls every frame
useFrame((state) => state.controls.update());
return <OrbitControls args={[camera, domElement]} enableDamping dampingFactor={0.1} />;
};
const GlobeComponent = ({ width, height }) => {
return (
<Canvas style={{ width: width, height: height }}>
<Suspense fallback={null}>
<ambientLight intensity={0.25} />
<pointLight position={[2, 0, 5]} />
<Globe
// Ensure you're setting props correctly according to react-three-globe's API
hexPolygonsData={countries.features}
// Convert data formats and properties as needed to fit the API for Globe component
// Set up other props as per the required data transformation
/>
</Suspense>
<CameraControls />
</Canvas>
);
};
export default GlobeComponent;
User
so i just found the cause of the error: "It seems there was a misunderstanding about the usage of react-three-globe. This package exports a default function that you can use to create a globe, but it doesn’t work directly with the @react-three/fiber’s Canvas component" The code needs to be refactored to use react-globe.gl instead: import React, { Suspense, useRef } from 'react';
import { Canvas, extend, useThree, useFrame } from '@react-three/fiber';
import { PerspectiveCamera, OrbitControls } from '@react-three/drei';
import { Globe } from 'react-three-globe';
import countries from './files/globe-data-min.json';
import travelHistory from './files/my-flights.json';
import airportHistory from './files/my-airports.json';
Thank you for the clarification. react-three-globe might not be compatible with @react-three/fiber Canvas as you've described. Instead, you should use globe.gl, which works seamlessly as a React component but doesn't directly integrate into the @react-three/fiber ecosystem.
globe.gl is a React-friendly library for creating globe visualizations based on Three.js, but it manages its own Three.js setup internally rather than using @react-three/fiber's declarative approach.
Here's how you can refactor your GlobeComponent to use globe.gl:
First, install the appropriate package:
sh
npm install globe.gl
Then update your GlobeComponent to use globe.gl:
jsx
import React from 'react';
import Globe from 'globe.gl';
import countries from './files/globe-data-min.json';
import travelHistory from './files/my-flights.json';
import airportHistory from './files/my-airports.json';
const GlobeComponent = ({ globeWidth, globeHeight }) => {
// Note that globe.gl is not a React component; you'll need to use a ref to create the globe
const globeEl = useRef();
// useEffect will allow us to initialize the globe and define its properties
useEffect(() => {
// Initialize the globe
const globeInstance = Globe()(globeEl.current)
.globeImageUrl('../components/files/earth-night.jpg')
.backgroundImageUrl('../components/files/night-sky.png')
.hexPolygonsData(countries.features)
.hexPolygonColor((e) =>
["KEN", "CHN", "FRA", "ZAF", "JPN", "USA", "AUS", "CAN"].includes(e.properties.ISO_A3)
? "rgba(255,255,255, 1)"
: "rgba(255,255,255, 0.5)"
)
.arcsData(travelHistory.flights)
.arcColor((e) => (e.status ? "#9cff00" : "#ff2e97"))
.arcDashLength(0.9)
.arcDashGap(1)
.arcDashAnimateTime(4000)
.pointsData(airportHistory.airports)
.pointColor(() => "#ffffff")
.pointAltitude(0.1)
.pointRadius(0.1)
.labelsData(airportHistory.airports)
.labelLat((e) => e.lat)
.labelLng((e) => e.lng)
.labelText((e) => e.city)
.labelSize((e) => e.size)
.labelColor(() => "#ffffff")
.labelAltitude(0.01);
// Destroy globe instance when unmounting to prevent memory leaks
return () => globeInstance._destructor();
}, [globeWidth, globeHeight]);
return (
<div ref={globeEl} style={{ width: globeWidth, height: globeHeight }} />
);
};
export default GlobeComponent;
User
i want you to reformat the parameters in order to add them to <GlobeComponent {params} />: .hexPolygonsData(countries.features)
.hexPolygonResolution(3)
.hexPolygonMargin(0.7)
.showAtmosphere(true)
.atmosphereColor("#ffffff")
.atmosphereAltitude(0.1)
.hexPolygonColor((e) => {
if (
["KEN", "CHN", "FRA", "ZAF", "JPN", "USA", "AUS", "CAN"].includes(
e.properties.ISO_A3
)
) {
return "rgba(255,255,255, 1)";
} else return "rgba(255,255,255, 0.5)";
});
To pass these parameters as props to the GlobeComponent, you would define each of the configuration options as props within the component and then pass those props to the Globe instance within GlobeComponent. Here is how you can refactor your component to accept these as props:
First, let's update your GlobeComponent to take props:
// Event listeners
function onWindowResize() {
camera.aspect = windowWidth / windowHeight;
camera.updateProjectionMatrix();
windowHalfX = windowWidth;
windowHalfY = windowHeight;
renderer.setSize(windowWidth, windowHeight);
}
function onMouseMove(event) {
mouseX = event.clientX - windowHalfX;
mouseY = event.clientY - windowHalfY;
// console.log("x: " + mouseX + " y: " + mouseY);
}
// Animation
function animate() {
camera.lookAt(scene.position);
controls.update();
renderer.render(scene, camera);
frameId = requestAnimationFrame(animate);
}
useEffect(() => {
// Initialize core ThreeJS elements
function init() {
// Initialize renderer
renderer = new WebGLRenderer({ antialias: true, alpha: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(globeWidth, globeHeight);
renderer.setClearColor(0x000000, 0);
containerRef.current.appendChild(renderer.domElement);
// Initialize scene, light
scene = new Scene();
scene.add(new AmbientLight(0xbbbbbb, 0.4));
// Initialize camera, light
camera = new PerspectiveCamera();
camera.aspect = globeWidth / globeHeight;
camera.updateProjectionMatrix();
var dLight = new DirectionalLight(0xffffff, 0.8);
dLight.position.set(-800, 2000, 400);
camera.add(dLight);
var dLight1 = new DirectionalLight(0x7982f6, 1);
dLight1.position.set(-200, 500, 200);
camera.add(dLight1);
var dLight2 = new PointLight(0x8566cc, 0.5);
dLight2.position.set(-200, 500, 200);
camera.add(dLight2);
camera.position.z = 400;
camera.position.x = 0;
camera.position.y = 0;
scene.add(camera);
// Additional effects
scene.fog = new Fog(0x535ef3, 400, 2000);
// Helpers
// const axesHelper = new THREE.AxesHelper(800);
// scene.add(axesHelper);
// var helper = new THREE.DirectionalLightHelper(dLight);
// scene.add(helper);
// var helperCamera = new THREE.CameraHelper(dLight.shadow.camera);
// scene.add(helperCamera);
// Initialize controls
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dynamicDampingFactor = 0.01;
controls.enablePan = false;
controls.minDistance = Math.min(globeWidth, globeHeight) / 2;
controls.maxDistance = Math.min(globeWidth, globeHeight) / 2;
controls.rotateSpeed = 0.8;
controls.zoomSpeed = 1;
controls.autoRotate = false;
controls.minPolarAngle = Math.PI / 3.5;
controls.maxPolarAngle = Math.PI - Math.PI / 3;
}
// Initialize the Globe
function initGlobe() {
// Initialize the Globe
Globe = new ThreeGlobe({
waitForGlobeReady: true,
animateIn: true,
})
.hexPolygonsData(countries.features)
.hexPolygonResolution(3)
.hexPolygonMargin(0.7)
.showAtmosphere(true)
.atmosphereColor("#ffffff")
.atmosphereAltitude(0.1)
.hexPolygonColor((e) => {
if (
["KEN", "CHN", "FRA", "ZAF", "JPN", "USA", "AUS", "CAN"].includes(
e.properties.ISO_A3
)
) {
return "rgba(255,255,255, 1)";
} else return "rgba(255,255,255, 0.5)";
});
// NOTE Arc animations are followed after the globe enters the scene
timeoutId = setTimeout(() => {
Globe.arcsData(travelHistory.flights)
.arcColor((e) => {
return e.status ? "#9cff00" : "#ff2e97";
})
.arcAltitude((e) => {
return e.arcAlt;
})
.arcStroke((e) => {
return e.status ? 0.5 : 0.3;
})
.arcDashLength(0.9)
.arcDashGap(4)
.arcDashAnimateTime(1000)
.arcsTransitionDuration(1000)
.arcDashInitialGap((e) => e.order * 1)
.labelsData(airportHistory.airports)
.labelColor(() => "#ffffff")
.labelDotOrientation((e) => {
return e.text === "NGA" ? "top" : "right";
})
.labelDotRadius(0.35)
.labelSize((e) => e.size)
.labelText("city")
.labelResolution(6)
.labelAltitude(0.01)
.pointsData(airportHistory.airports)
.pointColor(() => "#ffffff")
.pointsMerge(true)
.pointAltitude(0.07)
.pointRadius(0.10);
}, 1000);
Globe.rotateX(-Math.PI * (1 / 50));
Globe.rotateY(-Math.PI * (1 / 9));
Globe.rotateZ(-Math.PI / 60);
const globeMaterial = Globe.globeMaterial();
globeMaterial.color = new Color(0x3a228a);
globeMaterial.emissive = new Color(0x220038);
globeMaterial.emissiveIntensity = 0.1;
globeMaterial.shininess = 0.7;
// NOTE Cool stuff
// globeMaterial.wireframe = true;
scene.add(Globe);
}
init();
initGlobe();
onWindowResize();
animate();
window.addEventListener('resize', onWindowResize, false);
renderer.domElement.addEventListener('mousemove', onMouseMove);
console.log("Initializing globe animation");
return () => {
clearTimeout(timeoutId);
window.removeEventListener('resize', onWindowResize);
renderer.domElement.removeEventListener('mousemove', onMouseMove);
cancelAnimationFrame(frameId);
if (containerRef.current) {
// Perform more thorough clean-up here
// Dispose of the scene's children
while (scene.children.length > 0) {
const object = scene.children[0];
if (object.dispose) {
object.dispose();
}
scene.remove(object);
}
// Dispose of the renderer and any associated resources
renderer.dispose();
// Dispose of any controls, if necessary
if (controls && controls instanceof OrbitControls && controls.dispose) {
controls.dispose();
}
if (renderer.domElement.parentNode === containerRef.current) {
// Remove the renderer DOM element
containerRef.current.removeChild(renderer.domElement);
}
}
};
}, []);
return <div ref={containerRef} />;
};
export default GlobeComponent;
This is a significantly simplified version, and you may need to adjust it further to match your specific use case. With react-three-fiber, components like OrbitControls and PerspectiveCamera can be declared right alongside your objects within the Canvas component. React components for lighting (ambientLight, directionalLight, pointLight) are treated similarly to other objects.
Please note that react-three-globe might not have identical properties to three-globe; therefore, you would need to adjust your props (like arcsData, labelsData, pointsData etc.) to how react-three-globe expects them. You might also need to handle events differently in the context of React and react-three-fiber.
Finally, for more specialized features and customization, you might need to dig into the documentation or examples offered by react-three-fiber and react-three-globe. The ultimate goal of refactoring to react-three-fiber and react-three-globe is to fully embrace the React component paradigm, where you have less imperative code and more declarative JSX.
// Event listeners
function onWindowResize() {
camera.aspect = windowWidth / windowHeight;
camera.updateProjectionMatrix();
windowHalfX = windowWidth;
windowHalfY = windowHeight;
renderer.setSize(windowWidth, windowHeight);
}
function onMouseMove(event) {
mouseX = event.clientX - windowHalfX;
mouseY = event.clientY - windowHalfY;
// console.log("x: " + mouseX + " y: " + mouseY);
}
// Animation
function animate() {
camera.lookAt(scene.position);
controls.update();
renderer.render(scene, camera);
frameId = requestAnimationFrame(animate);
}
useEffect(() => {
// Initialize core ThreeJS elements
function init() {
// Initialize renderer
renderer = new WebGLRenderer({ antialias: true, alpha: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(globeWidth, globeHeight);
renderer.setClearColor(0x000000, 0);
containerRef.current.appendChild(renderer.domElement);
// Initialize scene, light
scene = new Scene();
scene.add(new AmbientLight(0xbbbbbb, 0.4));
// Initialize camera, light
camera = new PerspectiveCamera();
camera.aspect = globeWidth / globeHeight;
camera.updateProjectionMatrix();
var dLight = new DirectionalLight(0xffffff, 0.8);
dLight.position.set(-800, 2000, 400);
camera.add(dLight);
var dLight1 = new DirectionalLight(0x7982f6, 1);
dLight1.position.set(-200, 500, 200);
camera.add(dLight1);
var dLight2 = new PointLight(0x8566cc, 0.5);
dLight2.position.set(-200, 500, 200);
camera.add(dLight2);
camera.position.z = 400;
camera.position.x = 0;
camera.position.y = 0;
scene.add(camera);
// Additional effects
scene.fog = new Fog(0x535ef3, 400, 2000);
// Helpers
// const axesHelper = new THREE.AxesHelper(800);
// scene.add(axesHelper);
// var helper = new THREE.DirectionalLightHelper(dLight);
// scene.add(helper);
// var helperCamera = new THREE.CameraHelper(dLight.shadow.camera);
// scene.add(helperCamera);
// Initialize controls
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dynamicDampingFactor = 0.01;
controls.enablePan = false;
controls.minDistance = Math.min(globeWidth, globeHeight) / 2;
controls.maxDistance = Math.min(globeWidth, globeHeight) / 2;
controls.rotateSpeed = 0.8;
controls.zoomSpeed = 1;
controls.autoRotate = false;
controls.minPolarAngle = Math.PI / 3.5;
controls.maxPolarAngle = Math.PI - Math.PI / 3;
}
// Initialize the Globe
function initGlobe() {
// Initialize the Globe
Globe = new ThreeGlobe({
waitForGlobeReady: true,
animateIn: true,
})
.hexPolygonsData(countries.features)
.hexPolygonResolution(3)
.hexPolygonMargin(0.7)
.showAtmosphere(true)
.atmosphereColor("#ffffff")
.atmosphereAltitude(0.1)
.hexPolygonColor((e) => {
if (
["KEN", "CHN", "FRA", "ZAF", "JPN", "USA", "AUS", "CAN"].includes(
e.properties.ISO_A3
)
) {
return "rgba(255,255,255, 1)";
} else return "rgba(255,255,255, 0.5)";
});
// NOTE Arc animations are followed after the globe enters the scene
timeoutId = setTimeout(() => {
Globe.arcsData(travelHistory.flights)
.arcColor((e) => {
return e.status ? "#9cff00" : "#ff2e97";
})
.arcAltitude((e) => {
return e.arcAlt;
})
.arcStroke((e) => {
return e.status ? 0.5 : 0.3;
})
.arcDashLength(0.9)
.arcDashGap(4)
.arcDashAnimateTime(1000)
.arcsTransitionDuration(1000)
.arcDashInitialGap((e) => e.order * 1)
.labelsData(airportHistory.airports)
.labelColor(() => "#ffffff")
.labelDotOrientation((e) => {
return e.text === "NGA" ? "top" : "right";
})
.labelDotRadius(0.35)
.labelSize((e) => e.size)
.labelText("city")
.labelResolution(6)
.labelAltitude(0.01)
.pointsData(airportHistory.airports)
.pointColor(() => "#ffffff")
.pointsMerge(true)
.pointAltitude(0.07)
.pointRadius(0.10);
}, 1000);
Globe.rotateX(-Math.PI * (1 / 50));
Globe.rotateY(-Math.PI * (1 / 9));
Globe.rotateZ(-Math.PI / 60);
const globeMaterial = Globe.globeMaterial();
globeMaterial.color = new Color(0x3a228a);
globeMaterial.emissive = new Color(0x220038);
globeMaterial.emissiveIntensity = 0.1;
globeMaterial.shininess = 0.7;
// NOTE Cool stuff
// globeMaterial.wireframe = true;
scene.add(Globe);
}
init();
initGlobe();
onWindowResize();
animate();
window.addEventListener('resize', onWindowResize, false);
renderer.domElement.addEventListener('mousemove', onMouseMove);
console.log("Initializing globe animation");
return () => {
clearTimeout(timeoutId);
window.removeEventListener('resize', onWindowResize);
renderer.domElement.removeEventListener('mousemove', onMouseMove);
cancelAnimationFrame(frameId);
if (containerRef.current) {
// Perform more thorough clean-up here
// Dispose of the scene's children
while (scene.children.length > 0) {
const object = scene.children[0];
if (object.dispose) {
object.dispose();
}
scene.remove(object);
}
// Dispose of the renderer and any associated resources
renderer.dispose();
// Dispose of any controls, if necessary
if (controls && controls instanceof OrbitControls && controls.dispose) {
controls.dispose();
}
if (renderer.domElement.parentNode === containerRef.current) {
// Remove the renderer DOM element
containerRef.current.removeChild(renderer.domElement);
}
}
};
}, []);
return <div ref={containerRef} />;
};
export default GlobeComponent;
import React, { useRef } from 'react';
import { Canvas, extend, useFrame, useThree } from '@react-three/fiber';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { ReactGlobe } from 'react-three-globe';
import * as THREE from 'three';
// Import your data
import countries from './files/globe-data-min.json';
import travelHistory from './files/my-flights.json';
import airportHistory from './files/my-airports.json';
// Extend will make OrbitControls available as a JSX element called orbitControls for us to use.
extend({ OrbitControls });
const GlobeControls = () => {
const { camera, gl } = useThree();
const controlsRef = useRef();
useFrame(() => controlsRef.current.update());
return (
<orbitControls
ref={controlsRef}
args={[camera, gl.domElement]}
enableDamping
enablePan={false}
minDistance={150} // Adjust these to control zoom extents
maxDistance={300}
dampingFactor={0.05}
rotateSpeed={0.5}
minPolarAngle={Math.PI / 3.5}
maxPolarAngle={(2 * Math.PI) / 3}
/>
);
};
const CustomGlobe = () => {
const globeMaterial = new THREE.MeshPhongMaterial({
color: new THREE.Color(0x3a228a),
emissive: new THREE.Color(0x220038),
emissiveIntensity: 0.1,
shininess: 0.7,
});
// Render arcs, other elements, or effects here if needed
return (
<ReactGlobe
globeMaterial={globeMaterial}
// ...props (hexPolygonsData, arcsData, etc.)
// Convert and adapt your data to the props required by react-three-globe
// It's likely you'll need to handle the arcs, labels, and points in separate components
/>
);
};
const GlobeComponent = ({ windowWidth, windowHeight }) => {
const canvasRef = useRef();
return (
<Canvas
ref={canvasRef}
style={{
width: windowWidth,
height: windowHeight,
position: 'absolute',
}}
camera={{ position: [0, 0, 400], fov: 60 }}
onCreated={({ gl }) => {
gl.setClearColor(new THREE.Color(0x000000), 0);
gl.setSize(windowWidth, windowHeight);
}}
>
<ambientLight color={new THREE.Color(0xbbbbbb)} intensity={0.4} />
<directionalLight
position={[-800, 2000, 400]}
color={new THREE.Color(0xffffff)}
intensity={0.8}
/>
<directionalLight
position={[-200, 500, 200]}
color={new THREE.Color(0x7982f6)}
intensity={1}
/>
<pointLight
position={[-200, 500, 200]}
color={new THREE.Color(0x8566cc)}
intensity={0.5}
/>
<Suspense fallback={null}>
<CustomGlobe />
</Suspense>
<GlobeControls />
</Canvas>
);
};
export default GlobeComponent;
In this refactored version of GlobeComponent, we use the ReactGlobe component from the react-three-globe package, which likely has its way to accept details about polygons, arcs, etc.
Since the react-three-globe may not have all the identical features that three-globe has, the setup for specific properties would need to be adapted or recreated. For example, animations, arc properties, labels, and points may be handled differently, and you may need to create respective React components for them if they are not provided out of the box.
Lastly, ensure that all these changes still meet all your requirements before fully transitioning to this refactored version.
Please note the following:
The Canvas from @react-three/fiber will create the WebGL renderer, scene, and camera for you.
The PerspectiveCamera is made the default camera and is given a default position.
The Globe component is being used to create the 3D globe. Make sure to apply all the properties you need. If react-three-globe requires a different structure for arcs, points, and labels, you'll have to adapt the data structure accordingly.
We're loading the globeImageUrl and backgroundImageUrl assets via URLs, but you can use your local assets if you have them.
I used the Suspense component to wrap the Globe to handle asynchronous loading (which you can utilize for loading textures or other assets).
Event listeners like onWindowResize and onMouseMove from the previous code sample are handled by the react-three-fiber hooks/implementation, so they're not needed here.
This example assumes that the Globe component (react-three-globe) can accept the same or similar props as the ThreeGlobe module in your original code. Please make sure to adjust the prop names and data formats as necessary based on the react-three-globe documentation and API.
When you see something like OrbitControlsImpl, it's likely extracted from the use of extend:
jsx
extend({ OrbitControls: OrbitControlsImpl });
This syntax means you are extending the namespace used by react-three-fiber to include the OrbitControls that come from three/examples/jsm/controls/OrbitControls.js, but renaming them to OrbitControlsImpl to avoid conflicts or for clarity. However, since we import OrbitControls directly and not OrbitControlsImpl, there is no need for this name in the implementation, and you can disregard it.
Ensure that the Globe component from react-three-globe is exported properly from react-three-globe. If the Globe component is not a default export of react-three-globe, you'll need to import it with curly braces {}.
Also, verify the following:
All other imports (like country and history data) are correctly pointing to the files and that those files export the data you're trying to import.
Ensure that the Globe and other components are compatible with your version of react-three-fiber. Package updates can sometimes cause these types of issues.
By doing this, you should resolve the error concerning the invalid element type in your GlobeComponent.
I have removed all the @react-three/fiber Canvas and related components since they are not necessary here.
I've used React's useEffect hook to initialize the globe.gl instance and tie it to the component's lifecycle.
The globeEl ref is used to directly reference the DOM element, which is used to initialize the globe.
Remember that since globe.gl manages Three.js itself, you don't use it within a @react-three/fiber's Canvas. Instead, you'll manipulate it through its API after instantiating it with the DOM element it should use.
Please note, you need to make sure your static assets (e.g., images for the globe and the background) are correctly accessible from the location you're referencing in your React application. Adjust the paths accordingly if they're incorrect.
Now, when you want to use GlobeComponent, you pass the data and the configuration as props:
This refactor turns the prior method calls into a React component with props that can be easily managed and reused across your application. Adjust the styles and sizes as required for your design, and import the GlobeComponent into any module to render the globe with the props provided.