Earth

by Nightfly

HTML

<script src="//cdn.rawgit.com/mrdoob/three.js/master/build/three.js"></script>
<script src="//raw.githack.com/mrdoob/three.js/master/examples/js/controls/OrbitControls.js"></script>

CSS

body {
	  margin: 0;
}

JavaScript

let renderer, scene, camera, controls

const init = () => {
	scene = new THREE.Scene();
  camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 100);
  let textureLoader = new THREE.TextureLoader();
  
  camera.position.set(0.0, 1.5, 3.0);
   
  let ambientLight = new THREE.AmbientLight(0xffffff, 1);
  scene.add(ambientLight);
  
	let earthGeometry = new THREE.SphereGeometry(1, 64, 64);
  let earthMaterial = new THREE.ShaderMaterial({
  	uniforms: {
    	sunDirection: {value: new THREE.Vector3(1,0,0)},
      dayTexture: {value: textureLoader.load('https://i.ibb.co/C1G1RTX/earthmap1k.jpg')},
      nightTexture: {value: textureLoader.load('https://i.ibb.co/7Y6Gh7S/earthlights1k.jpg')}
    },
    vertexShader:`
				varying vec2 vUv;
            varying vec3 vNormal;
            varying vec3 vSunDir;

            uniform vec3 sunDirection;

				void main() {
					vUv = uv;
					vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
               vNormal = normalMatrix * normal;
               vSunDir = mat3(viewMatrix) * sunDirection;
					gl_Position = projectionMatrix * mvPosition;
				}
			`,
    fragmentShader:`
				uniform sampler2D dayTexture;
				uniform sampler2D nightTexture;

				varying vec2 vUv;
            varying vec3 vNormal;
            varying vec3 vSunDir;

				void main(void) {
					vec3 dayColor = texture2D(dayTexture, vUv).rgb;
					vec3 nightColor = texture2D(nightTexture, vUv).rgb;

					float cosineAngleSunToNormal = dot(normalize(vNormal), normalize(vSunDir));
					cosineAngleSunToNormal = clamp(cosineAngleSunToNormal * 3.0, -1.0, 1.0);
					float mixAmount = cosineAngleSunToNormal * 0.5 + 0.5;
					vec3 color = mix(nightColor, dayColor, mixAmount);
					gl_FragColor = vec4(color, 1.0);
				}
			`
  });
  let earth =  new THREE.Mesh(earthGeometry, earthMaterial);
  scene.add(earth);
  
  renderer = new THREE.WebGLRenderer({ antialias: true });

	controls = new THREE.OrbitControls(camera,...