Skip to content

Instantly share code, notes, and snippets.

@octopuss
Last active October 29, 2022 08:22
Show Gist options
  • Save octopuss/45bc111e82dd2af7b80f to your computer and use it in GitHub Desktop.
Save octopuss/45bc111e82dd2af7b80f to your computer and use it in GitHub Desktop.
Three.js demo showing rotating earth with drag drop and zooming functionality
<html>
<head>
<title>Tree.js demo earth</title>
</head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/three.js/84/three.min.js"></script>
<script type="text/javascript" src="http://threejs.org/examples/js/controls/TrackballControls.js"></script>
<body>
<script type="text/javascript">
var UP = 38;
var DOWN = 40;
var el = document.querySelector("body");
el.onkeydown = function(evt) {
evt = evt || window.event;
if(evt.keyCode==UP) {
camera.position.z+=0.5;
}
if(evt.keyCode==DOWN) {
if(camera.position.z==2) return;
camera.position.z-=0.5;
}
console.log(camera.position.z);
};
var scene = new THREE.Scene();
var controls, cube ;
var angularSpeed = 0.2;
var lastTime = 0;
var renderer = new THREE.WebGLRenderer();
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.z = 5;
scene.add(camera);
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
var geometry = new THREE.SphereGeometry( 1, 32, 32 );
var texture = new THREE.TextureLoader().load( "world.jpg" );
texture.wrapS = THREE.ClampToEdgeWrapping;
texture.wrapT = THREE.ClampToEdgeWrapping;
texture.minFilter = THREE.LinearFilter;
var material = new THREE.MeshLambertMaterial({
map: texture
});
controls = new THREE.TrackballControls( camera );
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
controls.keys = [ 65, 83, 68 ];
controls.addEventListener( 'change', render );
cube = new THREE.Mesh(geometry, material);
scene.add( cube );
// add subtle ambient lighting
var ambientLight = new THREE.AmbientLight(0xbbbbbb);
scene.add(ambientLight);
// directional lighting
var directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(1, 1, 1).normalize();
scene.add(directionalLight);
}
function animate() {
requestAnimationFrame( animate );
controls.update();
var time = (new Date()).getTime();
var timeDiff = time - lastTime;
var angleChange = angularSpeed * timeDiff * 2 * Math.PI / 1000;
cube.rotation.y += angleChange;
lastTime = time;
cube.rotation.x = Math.PI * 0.1;
render();
}
function render() {
renderer.render( scene, camera );
}
render();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment