JSFiddle - React, Tailwind, and code Playground
HTML
<script src="//cdn.rawgit.com/mrdoob/three.js/master/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<button id="buttonEarth">
To Earth
</button>
<button id="buttonSun">
To Sun
</button>
CSS
body {
margin: 0;
overflow: hidden;
}
JavaScript
let camera, scene, renderer, controls;
let sun, earth, currentObject;
const direction = new THREE.Vector3();
const camOffset = 10;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 100 );
camera.position.z = 10;
scene = new THREE.Scene();
const geometry = new THREE.SphereBufferGeometry( 1, 16, 16 );
const material = new THREE.MeshNormalMaterial( { wireframe: true } );
sun = new THREE.Mesh( geometry, material );
sun.scale.set( 2, 2, 2 );
scene.add( sun );
earth = new THREE.Mesh( geometry, material );
earth.position.x = 10;
earth.scale.set( 0.5, 0.5, 0.5 );
sun.add( earth );
const axesHelper = new THREE.AxesHelper( 5 );
scene.add( axesHelper );
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.enablePan = false;
controls.enableZoom = false;
currentObject = sun;
const buttonEarth = document.getElementById( 'buttonEarth' );
buttonEarth.addEventListener( 'click', () => currentObject = earth );
const buttonSun = document.getElementById( 'buttonSun' );
buttonSun.addEventListener( 'click', () => currentObject = sun );
}
function animate() {
requestAnimationFrame( animate );
// calculate the position in world space for the current target object (sun or earth)
currentObject.getWorldPosition( controls.target );
controls.update();
// update the transformation of the camera so it has an offset position to the current target
direction.subVectors( camera.position, controls.target );
direction.normalize().multiplyScalar( camOffset );
camera.position.copy( direction.add( controls.target ) );
sun.rotation.y += 0.002;
earth.rotation.y += 0.005;
renderer.render( scene, camera );
}