I am new to Three.js and have a basic question about loading a texture on a sphere. I am using the createEarthMaterial function in my code from the "Three.js Essentials" book but it is not working. The image file with the texture is named 'map2.png'. I have tried various solutions without success. Can anyone provide a helpful solution? Thank you in advance.
// defining global variables
var renderer;
var scene;
var camera;
var control;
var stats;
var cameraControl;
/**
* This function initializes the scene, camera, and objects when the window is loaded.
*/
function init() {
// creating a scene to hold elements such as objects, cameras, and lights
scene = new THREE.Scene();
// defining a perspective camera
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
// creating a WebGL renderer
renderer = new THREE.WebGLRenderer();
renderer.setClearColor(0xcccccc, 1.0);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMapEnabled = true;
// creating a SphereGeometry
var sphereGeometry = new THREE.SphereGeometry(15, 30, 30);
// creating material for Earth
var sphereMaterial = createEarthMaterial();
var earthMesh = new THREE.Mesh(sphereGeometry, sphereMaterial);
earthMesh.name = 'earth';
scene.add(earthMesh);
// setting camera position
camera.position.x = 35;
camera.position.y = 36;
camera.position.z = 33;
camera.lookAt(scene.position);
// adding controls
cameraControl = new THREE.OrbitControls(camera);
// setting up control object for GUI
control = new function () {
this.rotationSpeed = 0.005;
this.opacity = 0.6;
};
// adding renderer to HTML element
document.body.appendChild(renderer.domElement);
// calling render function
render();
}
function createEarthMaterial() {
var earthTexture = THREE.ImageUtils.loadTexture("map2.png");
var earthMaterial = new THREE.MeshBasicMaterial();
earthMaterial.map = earthTexture;
return earthMaterial;
}
/**
* Function to add control GUI
*/
function addControlGui(controlObject) {
var gui = new dat.GUI();
gui.add(controlObject, 'rotationSpeed', -0.01, 0.01);
}
function addStatsObject() {
stats = new Stats();
stats.setMode(0);
stats.domElement.style.position = 'absolute';
stats.domElement.style.left = '0px';
stats.domElement.style.top = '0px';
document.body.appendChild(stats.domElement);
}
function render() {
cameraControl.update();
scene.getObjectByName('earth').rotation.y += control.rotationSpeed;
renderer.render(scene, camera);
requestAnimationFrame(render);
}
/**
* Function to handle resize event
*/
function handleResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
window.onload = init;
window.addEventListener('resize', handleResize, false);