I’m trying to learn THREE.js, and I’m having trouble getting a simple skybox to show. I’ve tried a 100 different things, but nothing seems to work – the combination of too little documentation with a number of different releases has got me completely tied up. I’m at the end of my rope here!
I thought it might have to do with the time it takes to load the images, but I’ve tried putting in some “loader” code to no avail (taken out since it doesn’t seem to have done much). I’m willing to believe that I just didn’t do it the “right way” though – I’m having trouble finding examples that work with the current release.
<html>
<head> <title>Skybox Demo</title> <style>canvas { width: 100%; height: 100% }</style>
<body>
<script src="https://raw.github.com/mrdoob/three.js/master/build/three.js"></script>
<script>
var container;
var renderer;
var cameraCube, sceneCube;
var skyboxMesh;
var cubeTarget;
var mouseX = 0;
var mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
cameraCube = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 1000 );
sceneCube = new THREE.Scene();
// Load cube textures
var path = "textures/cube/";
var format = '.jpg';
var urls = [ path + 'px' + format, path + 'nx' + format,
path + 'py' + format, path + 'ny' + format,
path + 'pz' + format, path + 'nz' + format ];
var skyCubeTexture = THREE.ImageUtils.loadTextureCube(urls);
skyCubeTexture.format = THREE.RGBFormat;
// Cube shader
var shader = THREE.ShaderUtils.lib["cube"];
shader.uniforms["tCube"].texture = skyCubeTexture;
var material = new THREE.ShaderMaterial({
fragmentShader : shader.fragmentShader,
vertexShader : shader.vertexShader,
uniforms : shader.uniforms,
depthWrite : false,
side : THREE.BackSide
});
var skyboxMesh = new THREE.Mesh( new THREE.CubeGeometry(100, 100, 100), material);
sceneCube.add(skyboxMesh);
// Renderer
renderer = new THREE.WebGLRenderer( {antialias:true});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.autoClear = false;
container.appendChild( renderer.domElement );
}
function animate() {
render();
requestAnimationFrame( animate );
}
function render() {
var timer = - new Date().getTime() * 0.0002;
cameraCube.position.x = 10 * Math.cos( timer );
cameraCube.position.z = 10 * Math.sin( timer );
cameraCube.lookAt({x:0, y:0, z:0});
renderer.clear();
renderer.render(sceneCube, cameraCube);
}
</script>
</body>
</html>
Be very careful about copying examples from the net.
three.js is in alpha, and many of the examples floating around the net are out-of-date.
It is always best to start with the “official” three.js examples, as they work with the current library.
You need to assign the texture correctly:
This was a recent change.
three.js r.53