Threejs: Creating Waves in the Shape of a 'Plus' and 'X'

In my THREE.js scene, I currently have a circular wave effect being generated based on the formula in the ‘distance()’ function.

I’m curious to know whether it’s possible to modify the formula in order to create a wave pattern in the shape of an ‘X’ or a ‘Plus sign (+)’ instead.

var once = false;

// Code snippet for initializing the scene with specific settings and elements
class App {
  // Code for initializing the scene and setting up the necessary components
  init() {
    // Implementation details for initializing the scene
  }

  // Code snippet for adding directional light to the scene
  addDirectionalLight() {
    // Implementation details for adding directional light
  }

  // Code snippet for adding GUI controls to the scene
  addGUIControls() {
    // Implementation details for adding GUI controls
  }

  // Code snippet for adding a WebGL renderer to the scene
  addRenderer() {
    // Implementation details for adding a WebGL renderer
  }

  // Code snippet for adding ambient light to the scene
  addAmbientLight() {
    // Implementation details for adding ambient light
  }

  // Code snippet for clearing the scene
  clearScene() {
    // Implementation details for clearing the scene
  }

  // Code snippet for adding boxes to the scene
  addBoxes(scene) {
    // Implementation details for adding boxes to the scene
  }

  // Code snippet for drawing the wave pattern
  drawWave() {
    // Implementation details for drawing the wave pattern
  }

  // Code snippet for calculating the distance between two points
  distance(x1, y1, x2, y2) {
    // Implementation details for calculating the distance
  }

  // Code snippet for mapping a value to a different range
  map(value, start1, stop1, start2, stop2) {
    // Implementation details for mapping a value
  }

  // Remaining code snippets for adding essential components, animations, and resizing functionality
}

// Initialize the App and set up the scene
new App().init();

// CSS snippet for styling the HTML content
html {
  // CSS style settings for HTML
}

// Remaining CSS styles for the body, canvas, and other elements

  <main>
     <div class="stats"></div>
  </main>

  // External script tags for loading necessary libraries and dependencies
  <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/stats.js/r16/Stats.min.js"></script>
  <script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.2/dat.gui.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.3/TweenMax.min.js"></script>

Answer №1

"Add" or "Cross"

The "Add" operation is straightforward to execute. You simply calculate the distances from the center lines (horizontal and vertical).

const yd = j - this.row / 2; // distance from horizontal
const xd = i - this.col / 2; // distance from vertical

Then, you determine the minimum absolute value of each distance

const distance = Math.min(Math.abs(yd), Math.abs(xd));

After that, you utilize this distance as in the original method.

Execution

If you modify the draw function to the following code snippet, it will generate the add symbol you desire.

  drawWave() {
    var ii= 0, x, y;
    for (x = 0; x < this.col; x++) {
      const bRow = this.boxes[x];
      for (y = 0; y < this.row; y++) {
        const yd = y - this.row / 2;
        const xd = x - this.col / 2;
        const distance = Math.min(Math.abs(yd), Math.abs(xd));
        const angle = this.angle + this.map(distance, 0, this.waveLength, -100, 100);
        const size = this.map(Math.sin(angle), -1, -this.amplitude, 0.001, 1);

        bRow[y].scale.y = size;
        bRow[y].rotation.z = size;

        bRow[y].updateMatrix();
        this.mesh.setMatrixAt(ii++, bRow[y].matrix);
      }
    }
    this.mesh.instanceMatrix.needsUpdate = true;
    this.angle -= this.velocity;
  }

The cross

If you prefer a cross symbol, all you need to do is rotate x and y coordinates by 45 degrees. The following function achieves this effect.

  drawWave() {
    const xAx = Math.cos(Math.PI / 4);  // Axis 45 deg CW
    const xAy = Math.sin(Math.PI / 4);

    var ii= 0, x, y;
    for (x = 0; x < this.col; x++) {
      const bRow = this.boxes[x];
      for (y = 0; y < this.row; y++) {
        const xx = x - this.col / 2;
        const yy = y - this.row / 2;

        const xd = xx * xAx - yy * xAy;  // rotate
        const yd = xx * xAy + yy * xAx;

        const distance = Math.min(Math.abs(yd), Math.abs(xd));
        const angle = this.angle + this.map(distance, 0, this.waveLength, -100, 100);
        const size = this.map(Math.sin(angle), -1, -this.amplitude, 0.001, 1);

        bRow[y].scale.y = size;
        bRow[y].rotation.z = size;

        bRow[y].updateMatrix();
        this.mesh.setMatrixAt(ii++, bRow[y].matrix);
      }
    }
    this.mesh.instanceMatrix.needsUpdate = true;
    this.angle -= this.velocity;
  }

For optimal efficiency, consider implementing all the above calculations in the vertex shader.

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

Is there a method available for troubleshooting unsuccessful AJAX requests? Why might my request be failing?

Whenever I click on a button with the class "member-update-button," an alert pops up saying "got an error, bro." The error callback function is being triggered. Any thoughts on why this might be happening? No errors are showing up in the console. How can I ...

Exploring JS Object Property Access and Iteration with an Illustrative Example

Something strange is happening... the code snippet below generates a table displaying a list of SNMP object/values from any OID provided for walking. Strangely, the variable 'jason' is not behaving as expected. Initially, I am unable to access t ...

Acquire the S3 URL link for the uploaded file upon completion of the file upload process

Is there a way to securely upload and generate a public Amazon S3 URL for a PDF file when a user clicks on a specific link? I'd like to avoid exposing the actual link to the user by uploading it to S3. Here's a sample code snippet: module.expo ...

Translating from JavaScript to Objective-C using JSON

Can someone help me figure out how to correctly 'return' this JSON object in JavaScript? function getJSONData() { var points = '{\"points\": ['; var params = polyline.getLatLngs(); ...

What steps should I take with my Android PWA manifest and service workers?

I created a web application that I want to prompt Android users to download when they visit. To build my service workers and manifest, I utilized PWA Builder which can be found at Now that I have the manifest file ready, should I simply upload it to the r ...

Unable to access property 'map' of undefined - having trouble mapping data retrieved from Axios request

When working with React, I have encountered an issue while trying to fetch data from an API I created. The console correctly displays the response, which is a list of user names. However, the mapping process is not functioning as expected. Any insights or ...

Understanding the concept of hoisting in JavaScript for global variables and functions

I've been curious about hoisting. I understand that if a global function shares the same name as a global variable, the function will overwrite the variable's name. Is this correct? Here is an example code snippet. (function() { console.log ...

Dealing with React Native text overflowing beyond the screen width when using FlexWrap

I'm currently working on implementing a component in react native that consists of a row containing and components, but I'm struggling to achieve the desired outcome. Here's my current code: <View style={{ flexDirection: ...

There was an issue stating that valLists is not defined when paginating table rows with AngularJS and AJAX

I found a helpful code snippet on this website for implementing pagination in AngularJS. I'm trying to adapt it to work with data from a MySQL DB table called 'user', but I keep running into an issue where the valLists variable is undefined, ...

Why are Ajax calls returning 404 in Google Cloud Platform but working perfectly on local servers?

I recently came across a fantastic repository that offers a Java REPL directly in the browser. I decided to fork it and deploy it as a Google Cloud app to enhance its security with HTTPS. Everything seems to be working smoothly, except for one issue: Unf ...

Ways to retrieve a variable within the init() function

My current project involves using datatables along with ajax to display information dynamically. Below is the code snippet I am working with: // Setting up the module var DatatableAdvanced = function() { // Examples of Basic Datatables var _c ...

Click on a specific date on the calendar in the Javascript Django application to retrieve items based on

I'm currently working on a calendar application using JavaScript and Django. I am struggling to figure out how to display items based on the selected date when clicking on a day. Is there anyone who can suggest a solution? My assumption is that I may ...

Preventing AngularJS from Ignoring HTML Elements

Is there a way to calculate HTML content within an AngularJS object (such as {{names}}) that includes an '<a>' element? When I try to display it, the result looks like this: <a href="http://www.example.com">link text</a> I&ap ...

Credit for the Position swipejs

After integrating a swipeJS photo slideshow into my jQuery mobile application, I encountered an issue. I am trying to create points for counting the pictures similar to what is seen on this page: Although I have added the necessary HTML and CSS code to my ...

What is preventing me from utilizing require in vue-router's routes.js file?

Vue-router typically requires the standard setup as outlined below: In main.js, the routes.js file is required and it usually contains code similar to this: //routes.js import Register from './components/Register' import Login from './comp ...

When a radio button is checked, add a class to its parent element that has a specific class assigned to it

In order to dynamically add a class to a specific div element higher up the DOM hierarchy when a radio button is clicked, I am in need of assistance. There are multiple instances of these div elements with different radio buttons, so it is crucial that on ...

React Material-UI: Trouble with Checkbox Toggle

I'm encountering an issue with my React code where the checkbox is not toggling when clicked. Here is the link to the codesandbox: https://codesandbox.io/s/inspiring-kirch-q6p4h The checkbox state initialization looks like this: const [checkbox, set ...

Guide on transforming an array of objects into a fresh array

I currently have this array: const initialData = [ { day: 1, values: [ { name: 'Roger', score: 90, }, { name: 'Kevin', score: 88, }, { name: 'Steve&apo ...

A large canvas displaying a single optimized image

Hello, I have a large image on the canvas that measures around 10,000 pixels by 10,000 pixels. I am looking for zoom in/out functionality. Can you recommend what technology I should use? Should I consider splitting the image into smaller segments like Go ...

Utilizing Shaders in Three.js to Achieve Transparency Across a Given Radius

I'm attempting to use a Shader material in order to create a region of transparency surrounding my camera. In order to accomplish this, I am checking if a vertex falls within a specified radius. If it does, I am adjusting its color with a custom opaci ...