Issue arises when trying to insert an image avatar onto a globe in three.js

I have successfully implemented a rotating 3D globe using three.js with the code provided below.

HTML

<canvas id="canvas"></canvas>

JS

let camera;
let renderer;


function main()
{
    const canvas = document.querySelector('#canvas');


    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera(65, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.z = 2;
    scene.add(camera);

    renderer = new THREE.WebGLRenderer({canvas: canvas, antialias: true,});
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setPixelRatio(window.devicePixelRatio);

    renderer.autoClear = false;
    renderer.setClearColor(0x00000, 0.0);


    // create earthgeometry

    const earthgeometry = new THREE.SphereGeometry(0.6,32,32);

    const eatrhmaterial = new THREE.MeshPhongMaterial({
        roughness : 1,
        metalness:0,
        map: THREE.ImageUtils.loadTexture('texture/earthmap1k.jpg'),
        bumpMap: THREE.ImageUtils.loadTexture('texture/earthbump.jpg'),
        bumpScale: 0.3,
    });

    const earthmesh = new THREE.Mesh(earthgeometry,eatrhmaterial);

    scene.add(earthmesh);

    // set ambientlight

    const ambientlight = new THREE.AmbientLight(0xffffff, 0.1);
    scene.add(ambientlight);

    // set point light

    const pointerlight =  new THREE.PointLight(0xffffff,0.9);

    // set light position

    pointerlight.position.set(5,3,5);
    scene.add(pointerlight);

    const animate = () =>{
        requestAnimationFrame(animate);
        earthmesh.rotation.y += 0.0015;
        render();
    }

    const render = () => {
        renderer.render(scene,camera);
    }

    animate();
}

window.onload = main;

Now I am looking to add an image avatar that will be attached to the globe and rotate along with it. You can see the desired effect in this reference image:

I need assistance on how to achieve this effect in three.js. Any help or guidance is appreciated. Thank you!

If you want to test with my globe images, you can download them here: ( )

Answer №1

To incorporate an avatar image onto a plane geometry in your three.js project, follow these steps: First, create a plane geometry with the desired dimensions and make it transparent using a PNG texture. Then, attach the avatar image as a map parameter on the material, similar to how you added a globe texture. Attach the plane with the avatar image to the globe mesh and position it correctly. To ensure the avatar image always faces the camera, use the lookAt function.

//create plane geometry with width 1 and height 1, maybe you will need to adjust it 
const avatarGeometry: PlaneGeometry = new PlaneGeometry(1, 1, 1, 1);
// use png texture to make transparent object
const avatarTexture = THREE.ImageUtils.loadTexture('texture/avatar1.png'),
const avatarMaterial = new THREE.MeshStandardMaterial({
  map: texture,
  transparent: true,
});
const avatar = new Mesh(avatarGeometry, avatarMaterial);
// attach avatar to globe, it will rotate when globe rotate
earthmesh.attach(avatar)
avatar.position.set(2,2,2) //now you must position avatar outside of globe, so test it to get right position 

Update your animate function to:

const animate = () =>{
     requestAnimationFrame(animate);
     earthmesh.rotation.y += 0.0015;
     avatar.lookAt(camera.position) //to make avatars look at the camera
     render();
}

Although untested, this code should function properly.

For optimal positioning of your avatar, consider installing the three.js devtools for Chrome from this repository - https://github.com/oslabs-beta/BACE. These tools can aid in debugging and fine-tuning your project.

Alternatively, you can explore using the CSS3D renderer in three.js to render the avatar as an HTML element. This method is more complex but allows for combining 3D objects with HTML elements. Refer to the three.js examples for guidance: .

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

Minimizing the size of a production application's bundle

In a production application I am working on, the bundle size is currently 8.06MB. # Output from npm build File sizes after gzip: 1.67 MB build/static/js/3.73cf59a2.chunk.js 794.29 KB build/typescript.worker.js 131.13 KB build/css.worker.js 1 ...

Is it possible to utilize a .css file as the origin with @font-face?

Received a shortened path to a Gotham font... https://cloud.typography.com/[path shortened]/css/fonts.css Attempting to use it in a @font-face definition but facing issues with the src format: @font-face { font-family: 'Gotham'; src: url(" ...

What is the process of accessing JSON data transmitted from a Express server in JavaScript?

Working with a node server, I've set up a client-server model, meaning the client connects to "localhost" and express generates a response based on certain logic. While I'm able to send a JSON object through the response, I'm unsure of how t ...

Guide to using jQuery to load an image

I am using this code to load an image and display it within a dialog box. <div id="image_preview" title="Client Photo Preview"> <p><img src="" alt="client image" id="client_image_preview" /></p> </div> $("#client_image_p ...

I prefer not to have my preceding component re-rendered in React

I'm currently working on developing a user interface for a search engine using elasticsearch within React. One issue I'm facing is with the Pagination technique - when a user clicks on a result and then navigates back to the list of results, it r ...

I am looking to modify the highlighted table cell whenever the value within it changes

I am currently working on a small project related to the Stock Market. In this project, I need to dynamically change the style of the td element based on data fluctuations - green highlight for an increase and red highlight for a decrease. In the provid ...

What is the process for modifying the characteristics of an RMWC Component?

How can I dynamically change the icon attribute in my RMWC Button element when an onClick event occurs? <Button outlined icon={<CircularProgress />} onClick={(e)=> { // e.currentTarget.icon = ''; // console.log(e.c ...

Merge shared attributes into JSON with the help of JavaScript

I am looking to include a shared property in my JSON Object. Below is an example of the JSON object: data = [ { COUNTRY: 'USA', POPULATION: 300, }, { COUNTRY: 'USA', POPULATION: 50, }, { COUNTRY: 'Cana ...

Component in Angular2 encountering a null value

Unexpected situations may arise where "this" becomes null within a component. So far, I have encountered it in two scenarios: 1) When the promise is rejected: if (this.valForm.valid) { this.userService.login(value).then(result => { ...

Obtain the href attribute's value from an HTML document using Javascript

I'm facing an issue here. Currently, I am utilizing Grid.js (http://tympanus.net/codrops/2013/03/19/thumbnail-grid-with-expanding-preview/) for my project. Now, my goal is to incorporate a Lightbox with multiple thumbnails inside the dropout provide ...

Is it possible to eliminate the arrows from an input type while restricting the change to a specific component?

Is there a way to remove the arrows from my input field while still applying it only to the text fields within this component? <v-text-field class="inputPrice" type="number" v-model="$data._value" @change="send ...

Cannot Get jQuery .flip() to Work Automatically Every 2 Seconds

There are 3 words that I want to rotate on their x-axis every 2 seconds (repeating). Using jQuery: $(function () { count = 0; wordsArray = ["Innovation", "Creativity", "Success"]; setInterval(function () { count++; $("#words").text(wordsArray[co ...

What is the best way to incorporate multiple conditions within a React component?

When working in React, I have the ability to conditionally render any div using the following code snippet: {hasContent && <span>{value}</span> } Recently, I attempted to include two conditions as follows: {hasContent || hasDesc &am ...

A guide on integrating the MUI Timepicker with the newest 6 version using Formik

I am currently experimenting with the MUI React Timepicker component and facing an issue during integration with Formik for validation. The problem lies in the inability to bind values properly in the initialValues of the form. const [initialValues, setI ...

The ultimate guide to personalizing group titles in Angular UI-Select

Is there a way in Angular ui-select to customize the group label? I want to make it larger than the selection items as shown in the image below. https://i.stack.imgur.com/ofcak.png The list is currently grouped by country, but how can I adjust the size o ...

Exploring alternative methods of iterating over the values in a key-value pair within an AngularJS framework

My key-value pair consists of a long list of file names stored in the variable $ctrl.displayData- 143:"/this/is/a/very/long/fil22↵/this/is/a/very/long/file/path.php↵anotherone.php↵newfilel123.php" When I use ng-repeat to display these file names, t ...

Changing an object received as a prop in Vue.js

Is it acceptable to mutate values in a prop when passing an Object reference? In the process of developing a web application that involves passing numerous values to a component, I am exploring the most efficient method of handling value passing between c ...

Error encountered when WebDriverIO attempted to connect to Appium due to a lack of compatible capabilities

I'm currently facing an issue while attempting to link my virtual Android Device through Appium with my Webdriverio script for the purpose of automating some testing tasks. Here are the capabilities that I have set: capabilities: [{ // N ...

Enhance your JavaScript code by replacing Promise syntax with Async syntax and utilizing map() instead of a traditional For

I have a code snippet here that is functioning properly. However, I am interested in converting the Promise code in the middle of the function to Async code and replacing the for loop with map(). Can someone guide me on how to achieve this transformation ...

Displaying text files containing escaped characters using Express.js

I am facing an issue with my JSON object that has a text file within one of its fields. When I have Express render this text as "text/plain" in the response, it does not respect the '\n' line breaks and instead prints everything on one line. ...