Creating a 3D textured sphere using Three.js

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);

Answer №1

The importance of considering asynchronous image loading is often overlooked. A great example to understand this concept better can be found at . Here is a snippet of code demonstrating image loading:

var loader = new THREE.TextureLoader();
loader.load( 'textures/land_ocean_ice_cloud_2048.jpg', function ( texture ) {

    var geometry = new THREE.SphereGeometry( 200, 20, 20 );

    var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5 } );
    var mesh = new THREE.Mesh( geometry, material );
    group.add( mesh );

} );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering difficulty when integrating external JavaScript libraries into Angular 5

Currently, I am integrating the community js library version of jsplumb with my Angular 5 application (Angular CLI: 1.6.1). Upon my initial build without any modifications to tsconfig.json, I encountered the following error: ERROR in src/app/jsplumb/jspl ...

Encountering a Project Oxford error - HTTP 404 while trying to access Computer Vision API with Javascript

I am attempting to retrieve JSON data from Microsoft Project Oxford via an API call. Despite following the API reference, I encounter a 404 error when making the call. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js">< ...

After the rendering process, the React Component member goes back to a state of

One issue I encountered is related to a component that utilizes a separate client for making HTTP requests. Specifically, when trying to use the client within a click event handler, the call to this.client.getChannel() fails due to this.client being undefi ...

Utilizing an ajax request to invoke a PHP function rather than using a traditional

Within my page, I have included a file named functions.js. In this file, there is a line that reads: ajaxRequest.open("GET", "save.php?json=" + jsonstring + "&rand=" + rand, true); How can I invoke a php method using ajaxRequest? Additionally, I woul ...

Error: Node-Sass - Unable to download win32-x64-57_binding.node

Currently in the process of getting a retired colleague's program up and running, but when attempting to execute meteor run I encounter this error. While loading package materialize:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

Creating a "return" button for an editing form in AngularJS Datatables with the help of a form directive

Using AngularJS Datatables, I implemented a grid with additional "edit" and "delete" buttons in the last column. How is the grid/table rendered? HTML <!-- Required CSS and JS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/li ...

Utilizing CSS files to incorporate loading icons in a component by dynamically updating based on passed props

Is it possible to store icons in CSS files and dynamically load them based on props passed into a component? In the provided example found at this CodeSandbox Link, SVG icons are loaded from the library named '@progress/kendo-svg-icons'. Instea ...

Implementing proper data return in MVC4 through an Ajax call

When using ajax to call an action in a controller, the code may result like this: $.ajax({ type: "POST", url: "getUserInfo.json", data: "", success: function (data) { if (data.resultInfo.resu ...

Dealing with multiple parameters within the app.param() function

Currently, I am developing an API using Express.js and facing a challenge in implementing an app.param() function for handling the id parameter in a GET request: app.param('id', (req, res, next, id) => { const envelopeIndex = Number(id); ...

Managing the result efficiently when asp.net mvc ModelState IsValid is false

My colleagues and I are currently working on a CRUD application using .net mvc4. The project involves rendering dynamic content through jQuery based on customer choices. One challenge we face is the need to create multiple hidden inputs to pass additional ...

What is the correct method of implementing the "OnChange" event to a WooCommerce select element?

My task is to include the onchange="myFunction()" in the select menu below. However, because the select menu is part of woocommerce, I want to ensure that the onchange="myFunction()" remains intact even after updating my theme. How can I achieve this goal ...

What steps should I take to establish routes in my node and express application that allow for authentication through a designated method?

Currently, I am following the backend set up tutorial from auth0, and I have a question regarding how to organize my routes in a separate file rather than in the app.js. In the tutorial, they demonstrate var authenticate = jwt({ secret: new Buffer(proc ...

Having trouble with the functionality of the AngularJS Custom Service?

I have developed a straightforward service as shown below: var app = angular.module('myApp', ['ngRoute']); app.service('UserService', function() { this.user = {firstName:"",middleName:"",lastName:"",email:"",dob:""}; this.ad ...

I'm having trouble locating the documents I recently saved in my mongoose model

Here is my current challenge: I am populating a collection called "fruits" with some values. Once the data has been inserted, I want to use map to console.log each fruit individually. However, during the first attempt, instead of displaying a single fruit ...

Issue with integrating the jquery tokeniput plugin in asp.net mvc 3

Having trouble integrating the jQuery Tokeninput plugin into my MVC application. Something seems off with the setup... The Code I'm Using: <input type="text" id="MajorsIds" name="MajorsIds" /> <script type="text/jav ...

Tips for integrating both client-side and server-side validation techniques in your web application

After conducting some research, I have come across information indicating that it is feasible to implement both client-side and server-side validation simultaneously. However, my focus is not solely on learning JavaScript; I am also interested in utilizi ...

Utilizing object properties to dynamically update components in VueJS

Are you familiar with dynamically changing a component using object props? App.vue <template> <div id="app"> <component :is="current['test'].target.name"> </component> <input type="bu ...

Is there a way to automatically redirect the server URL when a file is modified?

I am currently experimenting with a function that is supposed to only display a message in the console without redirecting the actual URL of my server when a file is changed. watcher.add("/home/diegonode/Desktop/ExpressCart-master/routes/2.mk"); watche ...

List item with React Material UI tooltip

click here for image preview Exploring the idea of incorporating a customized tooltip component using React Material UI. The goal is to leverage the tooltip, list item, and list components provided by React Material UI. I have experimented with utilizing ...

zingcharts with multiple lines on x axis representing time

I am facing a rather interesting challenge with plotting data. I want to create a chart where time is the x-axis scale and multiple lines are plotted, each with varying time intervals between data points. While zingcharts has provided documentation on gene ...