Basic Three.js template scene, can´t animate - three.js

I'm really new in Three.js and javascript in general.
My question, I'm been trying to create some king of basic frankenstein template ( mainly based on Lee Stemkoski's examples) to use Three.js but as right know i can't make the cube spin infinitely, I have been watching tutorials and other examples but i can't make it work, any ideas why or how to solve it?
And
Any suggestions on how to improve this template scene?
Thanks in advance
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js Template</title>
<meta charset=utf-8>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,700' rel='stylesheet' type='text/css'>
<script src="js/three.js"></script>
<script src="js/Detector.js"></script>
<script src="js/Stats.js"></script>
<script src="js/OrbitControls.js"></script>
<script src="js/OBJLoader.js"></script>
<script src="js/MTLLoader.js"></script>
<script src="js/DDSLoader.js"></script>
<script src="js/THREEx.KeyboardState.js"></script>
<script src="js/THREEx.FullScreen.js"></script>
<script src="js/THREEx.WindowResize.js"></script>
</head>
<body>
<div id="info">
three.js Template Scene<br />
from Base scene
</div>
<div id="threeJSScene"></div>
<script>
// MAIN //
// standard global variables
var container, scene, camera, renderer, controls, stats, animate;
var keyboard = new THREEx.KeyboardState();
var clock = new THREE.Clock();
// initialization
init();
// animation loop / game loop
animate();
// FUNCTIONS //
function init()
{
// SCENE //
scene = new THREE.Scene();
//Add fog to the scene
// scene.fog = new THREE.FogExp2( 0xcccccc, 0.001 );
// CAMERA //
// set the view size in pixels (custom or according to window size)
// var SCREEN_WIDTH = 400, SCREEN_HEIGHT = 300;
var SCREEN_WIDTH = window.innerWidth,
SCREEN_HEIGHT = window.innerHeight;
// camera attributes
var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;
// set up camera
camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
// add the camera to the scene
scene.add(camera);
// the camera defaults to position (0,0,0)
// so pull it back (z = 400) and up (y = 100) and set the angle towards the scene origin
camera.position.set(0,150,400);
camera.lookAt(scene.position);
// RENDERER //
// create and start the renderer; choose antialias setting.
if ( Detector.webgl )
renderer = new THREE.WebGLRenderer( {alpha:true, antialias:true} );
else
renderer = new THREE.CanvasRenderer();
// Configure renderer size
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
//Change BG Color
//renderer.setClearColor( 0xAA20AA );
//Configure pixel aspect ratio
renderer.setPixelRatio( window.devicePixelRatio );
//Enable shadows
renderer.shadowMapEnabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
// Modify gamma
// renderer.gammaInput = true;
// renderer.gammaOutput = true;
//Attach div element to variable to contain the renderer
container = document.getElementById( 'threeJSScene' );
// alternatively: to create the div at runtime, use:
// container = document.createElement( 'div' );
// document.body.appendChild( container );
// attach renderer to the *container* div
container.appendChild( renderer.domElement );
// EVENTS //
// automatically resize renderer
THREEx.WindowResize(renderer, camera);
// toggle full-screen on given key press
THREEx.FullScreen.bindKey({ charCode : 'm'.charCodeAt(0) });
// CONTROLS //
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.addEventListener( 'change', render ); // remove when using animation loop
// enable animation loop when using damping or autorotation
//controls.enableDamping = true;
//controls.dampingFactor = 0.25;
controls.enableZoom = true;
//controls.update(); ----------> // required if controls.enableDamping = true, or if controls.autoRotate = true
// STATS //
// displays current and past frames per second attained by scene
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.bottom = '0px';
stats.domElement.style.zIndex = 100;
container.appendChild( stats.domElement );
// LIGHT //
// Add ambient light to Scene - Color(Blue) - Intensity
var Ambientlight = new THREE.AmbientLight (0x506699, 1);
scene.add(Ambientlight);
// Add light to Scene - Color(Red) - Intensity - Distance - decay
var light1 = new THREE.PointLight (0xff0000, 2, 400, 2);
light1.position.set(-60,150,-30);
light1.castShadow = true;
light1.shadowCameraVisible = true;
light1.shadow.mapSize.width = 1024 * 2;
light1.shadow.mapSize.height = 1024 * 2;
light1.shadowDarkness = 0.95;
light1.shadow.camera.near = 20;
light1.shadow.camera.far = 10000;
scene.add(light1);
// spotlight #1 -- yellow, dark shadow
var spotlight = new THREE.SpotLight(0xffff00);
spotlight.position.set(-60,150,-30);
spotlight.shadowCameraVisible = true;
spotlight.shadowDarkness = 0.95;
spotlight.intensity = 2;
// must enable shadow casting ability for the light
spotlight.castShadow = true;
scene.add(spotlight);
// GEOMETRY //
// Create a Cube Mesh //
var geometry = new THREE.BoxGeometry( 50, 50, 50 );
// Create a basic material
var material = new THREE.MeshStandardMaterial( {
color: "#ffffff",
side: THREE.DoubleSide,
//transparent: true,
//opacity: 0.5,
//wireframe: true,
//wireframeLinewidth: 5,
map: new THREE.TextureLoader().load('img/pattern.jpg'),
normalMap: new THREE.TextureLoader().load('img/pattern_NRM.png')
});
//Join the two attribute ( Geometry and material )
var mesh = new THREE.Mesh( geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.position.set(0, 50, 0); // Chance object position
//Add geometry to the scene
scene.add (mesh);
// Create a TorusKnot //
var TorusknotGeometry = new THREE.TorusKnotGeometry( 15, 5, 60, 25 );
var Torusknot = new THREE.Mesh( TorusknotGeometry, material); // We are using the same material created for the cube
Torusknot.castShadow = true;
Torusknot.receiveShadow = true;
Torusknot.position.set (0,100,0);
scene.add (Torusknot);
// Create a cube for the ground //
var groundGeometry = new THREE.BoxGeometry(200,200,10);
var ground = new THREE.Mesh( groundGeometry, material);
ground.castShadow = true;
ground.receiveShadow = true;
ground.position.set (0,0,0);
ground.rotation.x = 1.57;
scene.add (ground);
// Load in the mesh and add it to the scene.
var loader = new THREE.JSONLoader();
loader.load( "models/treehouse_logo.js", function(log){
var materiallogo = new THREE.MeshLambertMaterial({color: 0x55B663});
logo = new THREE.Mesh(log, materiallogo);
logo.scale.set (50,50,50);
logo.position.y = -1;
logo.castShadow = true;
logo.receiveShadow = true;
scene.add(logo);
});
// FLOOR //
// note: 4x4 checkboard pattern scaled so that each square is 25 by 25 pixels.
var floorTexture = new THREE.ImageUtils.loadTexture( 'img/checkerboard.jpg' );
floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;
floorTexture.repeat.set( 10, 10 );
// DoubleSide: render texture on both sides of mesh
var floorMaterial = new THREE.MeshBasicMaterial( { map: floorTexture, side: THREE.DoubleSide } );
var floorGeometry = new THREE.PlaneGeometry(1000, 1000, 1, 1);
var floor = new THREE.Mesh(floorGeometry, floorMaterial);
floor.castShadow = true;
floor.receiveShadow = true;
floor.position.y = -0.5;
floor.rotation.x = Math.PI / 2;
scene.add(floor);
// create a set of coordinate axes to help orient user
// specify length in pixels in each direction
var axes = new THREE.AxisHelper(100);
scene.add( axes );
// SKY //
// recommend either a skybox or fog effect (can't use both at the same time)
// without one of these, the scene's background color is determined by webpage background
// make sure the camera's "far" value is large enough so that it will render the skyBox!
var skyBoxGeometry = new THREE.CubeGeometry( 10000, 10000, 10000 );
// BackSide: render faces from inside of the cube, instead of from outside (default).
var skyBoxMaterial = new THREE.MeshBasicMaterial( { color: 0x9999ff, side: THREE.BackSide } );
var skyBox = new THREE.Mesh( skyBoxGeometry, skyBoxMaterial );
// scene.add(skyBox);
}
function update()
{
controls.update();
stats.update();
}
//Animate function
function animate()
{
requestAnimationFrame( animate );
render();
update();
}
// Render the scene - Always goes at the end
function render()
{
renderer.render( scene, camera );
}
</script>
</body>
</html>

To rotate your cube you'll need to add some value to the cube's rotation every frame. The reason this didn't work when you did it before is that the cube is defined in your init function and the render function doesn't have a reference to it.
So your fix requires two things:
Define your cube in a scope that both methods can "see"
Add some value to the rotation of your cube every frame
Inside of the init function you're defining your cube as mesh, so rename this to cube and remove var:
//Join the two attribute ( Geometry and material )
//var mesh = new THREE.Mesh( geometry, material); // Old
cube = new THREE.Mesh( geometry, material); // new
Removing var causes cube to become a global variable defined on the dom window rather than the init function. So your render function can "see" cube. So now all you have to do is rotate it!
function render()
{
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render( scene, camera );
}
I hope that helps!
and if you'd like to learn more about scope give this link a good read, it's helped me quite a bit.
https://toddmotto.com/everything-you-wanted-to-know-about-javascript-scope/

I ctrl + f'd the code, and you don't reference the rotation of the cube once. That would explain why it's not rotating. You can't will it to rotate, you need to actually write something that will change the values of the elements in your scene.
In order to continuously change the rotation of something, you need to reference or increment its rotation in the part of the code that loops.

Related

Three JS - window.onload first displays scene too small before resizing when opening browser

I am learning WebGL and I want to do something basic: whenever I open index.html, I want the rendered scene to fit the window. However, when I try running my code (that I adapted from the WebGL tutorials), for a split second, the scene is displayed at a small size before being resized. Visually, this is jarring. How do I prevent that from happening?
My two files:
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- <meta charset="utf-8" name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=1">-->
<meta charset="utf-8">
<title>ThreeJS Rotation</title>
<style>
body { margin: 0; }
</style>
</head>
<body>
<script type="module" src="js/script.js"></script>
</body>
</html>
js/script.js:
// import * as THREE from './three.module.js'
//
// import {OrbitControls} from "./OrbitControls";
// See https://stackoverflow.com/questions/63269365/three-js-does-not-provide-an-export-named-eventdispatcher-while-loading-orbitcon
import { OrbitControls } from 'https://unpkg.com/three#0.119.1/examples/jsm/controls/OrbitControls.js';
import * as THREE from 'https://unpkg.com/three#0.119.1/build/three.module.js';
// import { OrbitControls } from 'https://cdn.jsdelivr.net/npm/three#0.121.1/examples/jsm/controls/OrbitControls.js';
const scene = new THREE.Scene();
// Add background image
// scene.background = new THREE.Color(0x19d7f8);
const loader = new THREE.TextureLoader();
scene.background = loader.load('https://assets.imgix.net/hp/snowshoe.jpg')
// Arguments:
// 1) Field of Value (degrees)
// 2) Aspect ratio
// 3) Near clipping plane
// 4) Far clipping plane
const camera = new THREE.PerspectiveCamera( 50 , window.innerWidth / window.innerHeight, 0.1, 2000 );
camera.position.set(0, 0, 5 )
const renderer = new THREE.WebGLRenderer();
// // Need to set size of renderer. For performance, may want to reduce size.
// // Can also reduce resolution by passing false as third arg to .setSize
// renderer.setSize( window.innerWidth, window.innerHeight );
// Add the rendered to the HTML
document.body.appendChild( renderer.domElement );
function resizer() {
var width = window.innerWidth;
let height = window.innerHeight;
let backgroundImg = scene.background;
let bgWidth = backgroundImg.image.width;
let bgHeight = backgroundImg.image.height;
let texAspect = bgWidth / bgHeight;
let aspect = width / height;
let relAspect = aspect / texAspect;
scene.background.repeat = new THREE.Vector2( Math.max(relAspect, 1), Math.max(1/relAspect,1) );
scene.background.offset = new THREE.Vector2( -Math.max(relAspect-1, 0)/2, -Math.max(1/relAspect-1, 0)/2 );
renderer.setSize(width, height);
camera.aspect = width / height;
camera.updateProjectionMatrix()
}
window.onload = resizer
window.addEventListener('resize', resizer)
var controls = new OrbitControls(camera, renderer.domElement);
// Prevent Ctrl + Mouse from panning
controls.enablePan = false;
controls.update();
// A BoxGeometry is an object that contains all points (vertices) and fill (faces)
// of the cube
// const geometry = new THREE.BoxGeometry();
// // Allegedly, BoxBufferGeometry is faster
// const geometry = new THREE.BoxBufferGeometry();
// // Determines surface color (maybe texture?)
// const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
//
// // Mesh takes a geometry and applies the material to it
// const cube = new THREE.Mesh( geometry, material );
//
// scene.add( cube );
// Add arrow variables
const arrowDirection = new THREE.Vector3();
// Center of screen
const arrowPosition = new THREE.Vector3(0, 0, 0);
//
// const arrowPosition = new THREE.Vector3(0, 1, 0);
//
// const arrowPosition = new THREE.Vector3(0, 0, 0);
arrowDirection.subVectors( scene.position, new THREE.Vector3(1, 1, 1)).normalize();
const arrow = new THREE.ArrowHelper( arrowDirection, arrowPosition, 1, 0xffff00, 0.6, 0.4);
scene.add( arrow );
// This somehow creates a loop that causes the rendered to draw the scene
// every time the screen is refreshed (typically 60fps)
function animate() {
requestAnimationFrame( animate );
// arrow.rotation.x += 0.01;
// arrow.rotation.y += 0.01;
// cube.rotation.x += 0.01;
// cube.rotation.y += 0.01;
renderer.render( scene, camera );
controls.update();
}
animate();
You can try to set the renderer size before adding the renderer canvas to the dom
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height);
document.body.appendChild( renderer.domElement );

apply two textures on a plane in Three.js

Is it possible to add two textures at the same time on a plane? Or a cube?
I would like to apply one texture at the top half of a plane and a different one at the bottom half.
Something like this:
this is what I set so far
var geometry = new THREE.PlaneGeometry( 2, 2 );
var loader = new THREE.TextureLoader();
var texture = loader.load( 'textures/stone.png');
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set( 4, 4 );
var material = new THREE.MeshBasicMaterial( { map: texture } );
var mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
You'll want to segment your geometry, and use multi-materials.
This means you'll use the widthSegments and heightSegments parameters of PlaneGeometry to define a plane with more than just two faces. This is necessary because each face can only have one material (unless you're doing some seriously fancy blending).
Once you have a segmented plane, you can assign the materialIndex of each face to point to a separate material.
You'll also define your mesh using an array of materials, rather than just one--each face's materialIndex references an index in the materials array.
The last thing to do, which I'll leave up to you, is to adjust the face UVs and texture repeating/wrapping to achieve the effect you're seeking.
If you have further questions on this topic, leave a comment, and I'll try to address them.
// https://cdnjs.cloudflare.com/ajax/libs/three.js/89/three.js
// https://threejs.org/examples/js/controls/TrackballControls.js
/**********************/
/* Initialization */
/**********************/
var renderer = new THREE.WebGLRenderer( {
canvas: document.getElementById( "view" ),
antialias: true,
alpha: true
} );
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 28, 1, 1, 1000 );
camera.position.z = 50;
camera.add( new THREE.PointLight( 0xffffff, 1, Infinity ) );
scene.add( camera );
var controls = new THREE.TrackballControls( camera, renderer.domElement );
controls.addEventListener( "change", render );
/**********************/
/* Populate the Scene */
/**********************/
var texLoader = new THREE.TextureLoader();
var tex1 = texLoader.load( "https://upload.wikimedia.org/wikipedia/commons/2/2b/WallRGB.png", render ); // bricks
var tex2 = texLoader.load( "https://upload.wikimedia.org/wikipedia/commons/6/68/NGC772_-_SDSS_DR14.jpg", render ); // space
var mat1 = new THREE.MeshLambertMaterial( { map: tex1 } );
var mat2 = new THREE.MeshLambertMaterial( { map: tex2 } );
// First, segment your geometry however you need it.
// This one is segmented into 1 horizontal segment with 2 vertical segments.
var planeGeo = new THREE.PlaneGeometry( 10, 10, 1, 2 );
// Next you need to set up your faces to use specific materials.
planeGeo.faces[ 0 ].materialIndex = 0;
planeGeo.faces[ 1 ].materialIndex = 0;
planeGeo.faces[ 2 ].materialIndex = 1;
planeGeo.faces[ 3 ].materialIndex = 1;
// You can create a mesh using an array of materials, referenced by materialIndex.
var mesh = new THREE.Mesh( planeGeo, [ mat1, mat2 ] );
scene.add( mesh );
/**********************/
/* Render Function */
/**********************/
function render () {
renderer.render( scene, camera );
}
render();
/**********************/
/* Animation Loop */
/**********************/
function animate () {
requestAnimationFrame( animate );
controls.update();
}
animate();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="chrome=1,IE=edge">
<title>TEST</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/89/three.js"></script>
<script src="https://threejs.org/examples/js/controls/TrackballControls.js"></script>
</head>
<body>
<canvas id="view" width="500" height="500" style="border: 1px black solid;"></canvas>
<script src="test.js"></script>
</body>
</html>
Complementing #TheJim01's answer, the code below will, adjust the UV coordinates on the floor geometry so that they will tile:
var tileSize = 24;
var textureSize = 256;
var floorScale = tileSize/textureSize;
floorGeometry.faceVertexUvs.forEach(layer => layer.forEach((face, i) => {
const base = layer[i % 2];
if (i % 2) {
face[0].x = 0;
face[0].y = floorScale;
face[1].x = floorScale;
face[1].y = floorScale;
face[2].x = floorScale;
face[2].y = 0;
} else {
face[0].x = 0;
face[0].y = 0;
face[1].x = 0;
face[1].y = floorScale;
face[2].x = floorScale;
face[2].y = 0;
}
}));

EdgesHelper loses its mesh when scene is rotated

I've drawn a mesh with a edgeshelper.
When I rotate the scene using the mouse, the edges seems to react twice as fast the mesh.
The result is that the edges don't "fit" around the mesh anymore when the scene is rotated.
What am I doing wrong ?
<html>
<body onmousemove="bmousemove(event);">
<script src="three.min.js"></script>
<script>
var prevX = 0, prevY = 0;
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight, 1,10000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
geometry = new THREE.BoxGeometry( 10, 20, 40, 1, 1, 1 );
material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
object = new THREE.Mesh( geometry, material );
edges = new THREE.EdgesHelper( object, 0xffffff );
camera.position.z = 100;
scene.add( object );
scene.add( edges );
render();
function render()
{
requestAnimationFrame(render);
renderer.render(scene, camera);
}
function bmousemove(e)
{
if (prevX == 0)
{
prevX = e.clientX;
prevY = e.clientY;
}
scene.rotation.y += (e.clientX - prevX) / 100;
scene.rotation.x += (e.clientY - prevY) / 100;
prevX = e.clientX;
prevY = e.clientY;
}
</script>
</body>
</html>
I'm using version r71 under Windows 7
Yes, this is a consequence of how EdgesHelper(and some of the other helpers) have been implemented.
If you want to use EdgesHelper, you have to adhere to two rules:
EdgesHelper must be added to the scene, directly.
The scene can't have a transform applied (for example, be rotated).
Consequently, you will have to rotate the mesh, instead.
three.js r.71

camera inside a sphere

I want to create a skydome and made the shpere, texture loading also fine but I cannot move the camera inside the sphere.
The sphere disappears. I know it is an amateur issue but cannot see the inside of the sphere.
Is it some kind of cutting or Z-buffer issue?
How can I fix it?
My code:
<html>
<head>
<script src="js/jquery-1.8.3.min.js"></script>
<script src="js/three.min.js"></script>
</head>
<body>
<div id="container">
</div>
<script>
function addSpaceSphere( ){
// set up the sphere vars
var radius = 200,
segments = 16,
rings = 16;
var material = new THREE.MeshPhongMaterial({
color:0xFFFFFF,
map: THREE.ImageUtils.loadTexture( 'textures/SPACE014SX.png' )
});
var sphere = new THREE.Mesh(
new THREE.SphereGeometry(
radius,
segments,
rings
),
material
);
// add the sphere to the scene
scene.add(sphere);
}
function addLights(){
// create a point light
var ambient = new THREE.AmbientLight( 0xFFFFFF );
scene.add( ambient );
}
function render() {
camera.lookAt( focus );
camera.updateProjectionMatrix();
renderer.render( scene, camera );
}
function animate() {
requestAnimationFrame( animate );
render();
}
function createScene(){
// add the camera to the scene
scene.add(camera);
// the camera starts at 0,0,0
// so pull it back
camera.position.x = 0;
camera.position.y = 0;
camera.position.z = 300;
// start the renderer
renderer.setSize(WIDTH, HEIGHT);
$container.append(renderer.domElement);
addSpaceSphere( );
addLights();
animate();
}
var WIDTH = window.innerWidth;
var HEIGHT = window.innerHeight;
var VIEW_ANGLE = 45,
ASPECT = WIDTH / HEIGHT,
NEAR = 0.01,
FAR = 10000;
var focus = new THREE.Vector3( 0, 0, 0 );
var isUserInteracting = false,
onPointerDownPointerX = 0, onPointerDownPointerY = 0,
lon = 0, onPointerDownLon = 0,
lat = 0, onPointerDownLat = 0,
phi = 0, theta = 0;
var $container = $('#container');
// create a WebGL renderer, camera
// and a scene
//var renderer = new THREE.CanvasRenderer();
var renderer = new THREE.WebGLRenderer();
var camera = new THREE.PerspectiveCamera(
VIEW_ANGLE, ASPECT, NEAR, FAR
);
var scene = new THREE.Scene();
createScene();
</script>
</body>
make the skydome material double-sided -- it's being culled. Set the 'side' attribute to THREE.DoubleSide
(or THREE.BackSide should work too, if the camera is ONLY inside the sphere)

Cannot load textures

I'm struggleing with texture load issues.
All I see is a black sphere. :(
Any help would be awesome! Do i make something wrong?
Browser downloads the image, no issues on the console.
Checked in every browser with the same result.
OS: Mac 10.8.2
Here is my code:
<html>
<head>
<script src="js/jquery-1.8.3.min.js"></script>
<script src="js/three.min.js"></script>
</head>
<body>
<div id="container">
</div>
<script>
function addSpaceSphere( ){
// set up the sphere vars
var radius = 125,
segments = 16,
rings = 16;
var material = new THREE.MeshPhongMaterial({
color:0xFFFFFF,
map: THREE.ImageUtils.loadTexture( 'textures/SPACE014S.png' ) ,
});
var sphere = new THREE.Mesh(
new THREE.SphereGeometry(
radius,
segments,
rings
),
material
);
// add the sphere to the scene
scene.add(sphere);
}
function addLights(){
// create a point light
var ambient = new THREE.AmbientLight( 0xFFFFFF );
scene.add( ambient );
// create a point light
var pointLight = new THREE.PointLight(0xFFFFFF);
// set its position
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;
// add to the scene
scene.add(pointLight);
}
function createScene(){
// add the camera to the scene
scene.add(camera);
// the camera starts at 0,0,0
// so pull it back
camera.position.x = 0;
camera.position.y = 0;
camera.position.z = 300;
// start the renderer
renderer.setSize(WIDTH, HEIGHT);
$container.append(renderer.domElement);
addSpaceSphere( );
addLights();
renderer.render(scene, camera);
}
function onWindowResize( event ) {
var newEarthContainerWidth = earthContainer.offsetWidth;
var newWindowHeight = window.innerHeight;
var newScale = newEarthContainerWidth / earthContainerWidth;
sphere.geometry.__dirtyVertices = true;
sphere.scale.x = sphere.scale.y = sphere.scale.z = newScale;
renderer.setSize( newEarthContainerWidth, newWindowHeight );
camera.aspect = newEarthContainerWidth / newWindowHeight;
camera.updateProjectionMatrix();
camera.radius = ( newEarthContainerWidth + newWindowHeight ) / 4;
}
var WIDTH = window.innerWidth;
var HEIGHT = window.innerHeight;
var VIEW_ANGLE = 45,
ASPECT = WIDTH / HEIGHT,
NEAR = 0.1,
FAR = 10000;
var $container = $('#container');
// create a WebGL renderer, camera
// and a scene
//var renderer = new THREE.CanvasRenderer();
var renderer = new THREE.WebGLRenderer();
var camera = new THREE.PerspectiveCamera(
VIEW_ANGLE, ASPECT, NEAR, FAR
);
var scene = new THREE.Scene();
createScene();
window.addEventListener( 'resize', onWindowResize, false );
</script>
</body>
You are calling
renderer.render( scene, camera );
only once, and probably before the texture completes loading.
Add an animation loop.
function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
}
animate();

Resources