Creating a graph of the cosine function by tracking the movement of the mouse

Objective: Modify the length of the cosine wave based on the horizontal position of the mouse cursor. The key function to focus on is mouseMoveHandler.

(function(window,document,undefined){
var canvas = document.getElementById('canvas'),
    rect = canvas.getBoundingClientRect(),
    x = rect.right,
    twopi = 2*Math.PI, 

    scene = new THREE.Scene(),
    camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
    camera.position.z = 10;

var renderer = new THREE.WebGLRenderer();
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

/*Key Function*/
var material = new THREE.LineBasicMaterial({color: 0xf9f9f9}),
    geometry = new THREE.Geometry(),
    line = new THREE.Line(geometry, material);


var mouseMoveHandler = function(e){
  var j = 0,
      a = e.clientX/x,
      b = a*(3*twopi);

  for(i=0; i < b; i += .01){
    geometry.vertices[j] = new THREE.Vector3(i, Math.cos(i), 0);
    j = j+1;
    geometry.verticesNeedUpdate = true;
  } 

  scene.add(line);
}

var loop = function() {
    window.requestAnimationFrame(loop);
    renderer.render(scene, camera);
    }

window.onmousemove = mouseMoveHandler;
loop();

})(this,document);

My anticipated outcome for this code is to draw a cosine wave and dynamically adjust the line segments based on the mouse movement. However, the line is only generated once when the mouse enters the screen and does not update thereafter.

I am uncertain about how to properly utilize verticesNeedUpdate, which leads me to suspect that it might be related to the issue at hand.

In my previous attempts, I used .push to add values to the 'geometry.vertices' array, but this only allowed the wave to increase in length and not decrease when the mouse moved to the left.

Answer №1

Take a look at the information provided on the ThreeJS Wiki:

It's important to note that you can update the content of buffers but you cannot resize them easily without significant cost. It's essentially the same as creating a new geometry altogether.

To mimic resizing, one approach is to pre-allocate a larger buffer and then manage unnecessary vertices by collapsing them or hiding them.

While your vertices may be updating correctly, the geometry itself is limited to its original size when the vertices were first updated.

One way to address this limitation is by pre-allocating a fixed number of vertices.

Another option is to create a new geometry or line for each update, although this method is not very efficient.

Additionally, consider exploring BufferGeometry, which is recommended for achieving your goal. This involves pre-allocating a points buffer and then using geometry.setDrawRange() to adjust the geometry length based on your mouse position.

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

When a user clicks on an element, use jQuery to show a specific

I am looking to extract the Admission ID field within a separate function that triggers when a user clicks on a button. $(document).ready(function () { $.each(data.student, function (i, item){ trHTML += '<tr>'+ ...

Generating a 3D model and integrating it with a 3D terrain display on Mapbox

My goal is to integrate a 3D model as a custom layer on Mapbox using Three.js, alongside adding a 3D terrain on the map. I have followed the documented examples for incorporating a 3D model and 3D terrain from Mapbox. The issue I'm encountering is th ...

The parameter did not successfully transfer to the internal function within Firebase Cloud Functions

I am currently working on a Firebase cloud function that looks like this: exports.foo = functions.database .ref("/candidates/{jobTrack}/{candidateId}") .onCreate((snap, context) => { const candidate = snap.val().candidate; const jobTrack = ...

Making adjustments to text in HTML without altering the CSS or styling is proving to be challenging

When attempting to modify a h1 tag without changing the CSS, I encountered an issue. Below is the string with and without the JavaScript: String without JavaScript: https://i.sstatic.net/JWOmq.png String with JavaScript: https://i.sstatic.net/RNMur.png ...

after ajax post, enhance original object by merging with the latest server values

After making a call to the server and successfully saving some data, I need to update the JSON array object that I have with new values. Here is a snippet of my code: [ { "id": 1, "uuid": "ce54acea-db20-4716-bceb-2f3deb1b2b86", "name": null, ...

Conceal flexbox item depending on neighboring element dimensions or content

I've encountered an issue while using a flexbox to display two elements side by side. The left element contains text, while the right one holds a number. When the value in the right element has at least 7 digits ( > 999,999 or < -999,999), I ne ...

unable to retrieve the value of this.table property within a JavaScript class

In my JavaScript code, I have created a class that generates a MySQL model like so: class Model { constructor(options = {}, table) { this.options = options; this.table = table; this.create(); } create() { let queryString = `INSERT INT ...

Retrieve all direct message channels in Discord using DiscordJS

I need to retrieve all communication channels and messages sent by a bot. The goal is to access all available channels, including direct message (DM) channels. However, the current method seems to only fetch guild channels. client.channels.cache.entries() ...

The v-html command displays unprocessed HTML code on the webpage

This is a visual representation of my component: <template> <div v-html="someHtml"></div> </template> <script> export default { name: "test", props: { someHtml: String, }, } </script&g ...

The default expansion behavior of Google Material's ExpansionPanel for ReactJS is not working as expected

Currently, I am in the process of developing a ReactJS application that utilizes Google's Material-UI. Within this project, there is a child class that gets displayed within a Grid once a search has been submitted. Depending on the type of search con ...

Opening a browser tab discreetly and extracting valuable data from it

Greetings to the experts in Chrome Extension development, I am exploring ways to access information from a webpage without actually opening it in a separate tab. Is there a method to achieve this? Here's the scenario: While browsing Site A, I come a ...

Unable to transfer the output of a react query as a prop to a child

Working on my initial Next.js project, I encountered an issue with the article component that is rendered server-side. To optimize performance and reduce DOM elements, I decided to fetch tags for articles from the client side. Here's what I implemente ...

Customizing the main icon in the Windows 10 Action Center through a notification from Microsoft Edge

I am facing an issue with setting the top icon of a notification sent from a website in Microsoft Edge. Let's consider this code as an example: Notification.requestPermission(function (permission) { if (permission == "granted") { new ...

Sending data with React using POST request

Currently in my React application, I have a form that includes fields for username and password (with plans to add "confirm password" as well). When submitting the form, I need it to send JSON data containing the email and password in its body. The passwo ...

What are the differences in using ng-controller versus data-ng-controller?

When working with Angularjs, how do I determine whether to use data-ng-controller or ng-controller? In terms of current best practices for good software design, when is it appropriate to use each one? The information cited suggests that data-ng-controlle ...

Error message: Can't find Highcharts in (React JS) environment

I have been encountering an error ReferenceError: Highcharts is not defined, and I've been struggling with this issue for a few days now. Can you provide assistance? In my project, I have Dashboard and Chart files where I import the Chart components ...

I'm only seeing output on two of my input boxes - what's going on?

Currently in the process of learning JQUERY/HTML, I decided to create a shopping cart. My goal is to display the subtotal, tax, shipping costs, and total cost in input boxes. While I successfully displayed the sub total and shipping cost, I encountered an ...

What is the best way to insert a two-worded value into the value attribute of an input tag using Express-Handlebars?

Currently, I am using the code below to render the handlebars page: router.get("/update", function(req, res) { mysql.pool.query("SELECT * FROM workouts WHERE id = ?",[req.query.id], function(err, rows, fields) { if (err) { c ...

Steps for setting up Node.js or npm on XAMPP

Hello there, I'm new to all of this so please bear with me if I make any mistakes. As a beginner developer, I am currently working on developing a web application locally using XAMPP. My plan is to eventually deploy it using a hosted web service. XAM ...

Utilizing jQuery with live content to determine dimensions as required

Within my web application, I have a page that dynamically retrieves a view with both HTML and JavaScript. The JavaScript is responsible for rendering a chart into the retrieved view. The problem arises because the chart library I am utilizing (flot) necess ...