Creating a TextGeometry in THREE JS that Reacts to Mouse Movements

I have created a unique source code where the text rotates based on mouse position.

// Setting up the scene
            const scene = new THREE.Scene();
      let camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
      let renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
            let body = document.getElementsByTagName("body");
            let pageX = 0.5;
            let pageY = 0.5;

      renderer.setSize( window.innerWidth, window.innerHeight );

      document.getElementById("board").appendChild(renderer.domElement);

      // Handling window resize event
      window.addEventListener('resize', () => {
        renderer.setSize( window.innerWidth, window.innerHeight );
        camera.aspect = window.innerWidth / window.innerHeight;

        camera.updateProjectionMatrix();
      });

      camera.position.z = 20;

            // Adding light sources to the scene
            let directLight = new THREE.DirectionalLight('#fff', 4);
            directLight.position.set(0, 7, 5);
            scene.add(directLight);

            var light = new THREE.AmbientLight( 0x404040 ); // subtle white light
            scene.add( light );

            function animate (){
              requestAnimationFrame( animate );
                var loader = new THREE.FontLoader();
                loader.load( 'https://threejs.org/examples/fonts/helvetiker_regular.typeface.json', function ( font ) {
                    var geometry = new THREE.TextGeometry( 'Hello three.js!', {
                        font: font,
                        size: 3,
                        height: 0.5,
                        curveSegments: 4,
                        bevelEnabled: true,
                        bevelThickness: 0.02,
                        bevelSize: 0.05,
                        bevelSegments: 3
                    } );
                    geometry.center();
                    var material = new THREE.MeshPhongMaterial(
                        { color: '#dbe4eb', specular: '#dbe4eb' }
                    );
                    var mesh = new THREE.Mesh( geometry, material );

                    mesh.rotation.x = (pageY - 0.5) * 2;
                    mesh.rotation.y = (pageX - 0.5) * 2;

                    scene.add( mesh );
                } );
        renderer.render(scene, camera);
      }

      animate();

            // Tracking mouse movement for interaction
            document.body.addEventListener('mousemove', (event) => {

                pageX = event.pageX / window.innerWidth;
                pageY = event.pageY / window.innerHeight;

            });
      renderer.render(scene, camera);

        </script>

This is my unique approach to solving this issue. The current problem lies in creating multiple instances of the rotating text instead of having just one follow the mouse. Any help or advice would be greatly appreciated. Thank you!

Answer №1

It seems that you've already discovered the issue - reloading the font and recreating the mesh on every frame.

To solve this, consider moving the font loading and object creation into an initialization function so they only happen once.

The code inside the render loop should focus on updating the text's rotation based on mouse movement:

mesh.rotation.x = (pageY - 0.5) * 2;
mesh.rotation.y = (pageX - 0.5) * 2;

However, a new problem arises since `mesh` is a local object within the font loader callback function and not accessible outside. You can use the `.name` property in three.js to give your object a name like this:

var mesh = new THREE.Mesh(geometry, material);
mesh.name = "myText";
scene.add(mesh);

You can later reference this object using:

scene.getObjectByName("myText")

Here's a sample implementation:

// Your code goes here
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r120/three.min.js"></script>
<div id="container"></div>

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

Techniques for transferring form data from JavaScript to Java

Currently in my application, I have a signup form and I am facing an issue with storing the data in the backend. Since I am not well-versed in the backend development, I am struggling with this task. I'm using Netbeans 7.0 as my IDE and MySQL 5.6 for ...

Display a div element using AngularJS

Looking for a way to display a div using AngularJS, I came across some solutions on StackOverflow. However, implementing them did not work in my case. Here is my HTML code: <div id="myPanel" ng-controller="controllerDependance" ng-show="myvalue" clas ...

Ensure page is updated after an AJAX request in jQuery Mobile by refreshing the page

My jQueryMobile page structure in index.html looks like this: <div data-role="page"> <div data-role="header">...</div> <div data-role="content">...</div> <div data-role="footer">...</div> </div& ...

Creating a feature in Vuejs that allows for real-time card updates on the screen by sending a post request to the database and

After sending a post request to the database, I need to refresh my cardData array which gets its value from a get request in order to see the changes. The current saveDraft() function adds values to the cardData array, but it requires a page refresh or c ...

Adding an item to an array in Angular 2 using JavaScript!

In my Angular2 form, I have a field that consists of an array of objects. I've successfully created a table with a Delete Row button for each row and an Add Row button using the push() and slice() methods in JavaScript. However, there's a major ...

Display or Conceal Content Depending on the Button's Status

I am currently working on implementing an accordion style button for a project. I have configured my component to hide the list when the button is clicked, but I am encountering an issue where the list does not reappear. Additionally, I would like to inc ...

React.Children does not reveal the presence of any offspring

I am looking to implement react-native-maps-clustering in my project. However, this library only accepts markers that are direct children of the maps component. An example of how it should be structured: <MapView> <Marker/> <Marker/> ...

Tips for accessing <Field> values in redux-form version 7.0.0

class CustomForm extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick() { const { Add, noteList } = this.props; Add('this is title value' , 'this is ...

changing size when hovered over with the mouse is not consistent between entering and exiting

Hi there, I'm currently utilizing the transform: scale(); property on a website and could use some assistance with a particular issue I haven't been able to find an answer for online. Here is the code snippet I'm working with: HTML: <d ...

Firefox 44 experiencing issue with HTML 5 Video playing sounds unexpectedly

There has been an unusual observation of Firefox playing the sounds of all embedded videos on a page, even when the elements themselves are not actively playing. Clicking play on the video controls triggers new sound and video playback to start. All video ...

Does it have .hasOwnProperty and a significant value?

Today, I encountered a tricky situation involving the JavaScript Object.hasOwnProperty method. I was working on a form that creates properties on an object. The issue arose when dealing with a select box that had a value selected and then reset back to it ...

Ways to restrict input text to a specific set of values

When using an input text form, I need to ensure that users only insert values ranging from 1 to 10. However, my attempts to utilize a mask for customization have resulted in allowing values higher than 10. How can I restrict the input to only be allowed b ...

Unable to clear form using `$setPristine` command

Whenever I try to execute the code below to reset my form, I encounter an error: $scope.resetForm = function () { $scope.testForm.$setPristine(); } Here is the HTML snippet: <form name="testForm" > <label class="it ...

The file that is currently being downloaded has the .pptx extension, but it is being

Take a look at this code snippet: const generateDownload = ({ link, data, title, settings })=> { const newLink = document.createElement('a'); const blobUrl = link || URL.createObjectURL(new Blob([data], settings)); newLink.setAt ...

When the month picker is selected, my intention is to retrieve the true value. However, I am encountering an issue where it consistently returns the false value instead

I created a month picker similar to the image provided. After removing unnecessary code, I was left with only the part that generates questions. Initially, when the month picker renders, no value is selected. However, upon selecting a month, the value is d ...

Toggling forms with HTML <select> elements: A step-by-step guide

In the process of creating a web application, I am faced with the task of registering users based on their specific category. To accomplish this, I have incorporated a combo-box where users can indicate their user type. My objective is to display an appro ...

Having trouble getting the jQuery keydown trigger to function properly?

After the document has finished loading, I execute this script: $(function () { $("input").keydown(); }); This script is part of a chrome extension that runs on every page the user visits. However, it does not work on certain websites like Twitter ...

How can you prevent multiple instances of JavaScript objects from being disposed of after they have completed their task?

I'm facing an issue with the code snippet below: $(document).ready(function() { $('.container').ready(function() { var v = new Video($(this)); v.load(); }); }); I'm trying to prevent the object 'v&apos ...

Is the geometry shape in Three.js extended?

I am encountering an unusual issue in my Three.js project where a geometry appears to be excessively stretched vertically. My process involves dynamically loading an image and creating a planeGeometry to incorporate it into the scene. The image itself is ...

What is the best way to eliminate a vertical line from the canvas in react-chartjs-2?

Can someone please lend me a hand? I've been working on a project in React JS that involves using react-chartjs-2 to display charts. I'm trying to incorporate a range slider for the chart to manipulate values on the x-axis, as well as two vertic ...