Transforming a triangular shape into a square using Plane Geometry in THREE.js

I have an animation created with triangles in the link below. Is there a way to convert these triangular areas into squares? The animation currently has a line running through the middle when using "PlaneGeometry". Removing this line would turn the triangles into squares.

Check out the animation here

I want the final result to look like the image shown here.

( function( $ ) {
"use strict";
  
    $( function() {
        

        
        var $window                   = $( window ),
            windowWidth               = window.innerWidth,
            windowHeight              = window.innerHeight,
            rendererCanvasID          = '3D-background-three-canvas5';
        
    
        
        // Generate one plane geometries mesh to scene
        //------------------------------------- 
        var camera,
            scene,
            material,
            group,
            lights = [],
            renderer,
            shaderSprite,
            clock = new THREE.Clock();
        

        var geometry, plane, simplex;
        
        var factor = 300,
            speed = 0.0005, // terrain size
            cycle = 0, //move speed
            scale = 30; // smoothness
            
   

        init();
        render();

        function init() {
            //camera
            camera = new THREE.PerspectiveCamera( 60, windowWidth / windowHeight, 1, 10000 );
            camera.position.set( 0, 0, 100 );

        
            //Scene
            scene = new THREE.Scene();

            //HemisphereLight
            lights[ 0 ] = new THREE.PointLight( 0xff0000, 1, 0 );
            lights[ 1 ] = new THREE.PointLight( 0x0000ff, 1, 0 );
            lights[ 2 ] = new THREE.PointLight( 0xffffff, 1, 0 );

            lights[ 0 ].position.set( 0, 200, 0 );
            lights[ 1 ].position.set( 100, 200, 100 );
            lights[ 2 ].position.set( - 100, - 200, - 100 );

            scene.add( lights[ 0 ] );
            scene.add( lights[ 1 ] );
            scene.add( lights[ 2 ] );

            

            //WebGL Renderer        
            renderer = new THREE.WebGLRenderer( { 
                                    canvas   : document.getElementById( rendererCanvasID ), //canvas
                                    alpha    : true, 
                                    antialias: true 
                                } );
            renderer.setSize( windowWidth, windowHeight );

        
            // Immediately use the texture for material creation
            group = new THREE.Object3D();
            group.position.set(0,-300,-1000);
            group.rotation.set(29.8,0,0);

            
            
            geometry = new THREE.PlaneGeometry(4000, 2000, 128, 64);
            material = new THREE.MeshLambertMaterial({
                color: 0xffffff,
                opacity: 1,
                blending: THREE.NoBlending,
                side: THREE.FrontSide,
                transparent: false,
                depthTest: false,
                wireframe: true
            });
            plane = new THREE.Mesh(geometry, material);
            plane.position.set(0, 0, 0);
            
            simplex = new SimplexNoise();
            moveNoise();
            
            
            group.add(plane);
            scene.add(group);
            
            

            // Fires when the window changes
            window.addEventListener( 'resize', onWindowResize, false );
            
            
        }

        function render() {
            requestAnimationFrame( render );
            
            var delta     = clock.getDelta();

            //To set a background color.
            renderer.setClearColor( 0x000000 ); 
            
        
            //change noise values over time
            moveNoise();
            
            //update sprite
            cycle -= delta * 0.5;
            
            

            renderer.render( scene, camera );
            
            

            
        }


        function onWindowResize() {
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
            renderer.setSize( window.innerWidth, window.innerHeight );
        }



        function moveNoise() {
            var _iteratorNormalCompletion2 = true;
            var _didIteratorError2 = false;
            var _iteratorError2 = undefined;

            try {
                for (var _iterator2 = geometry.vertices[Symbol.iterator](), _step2; ! (_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
                    var vertex = _step2.value;
                    var xoff = vertex.x / factor;
                    var yoff = vertex.y / factor + cycle;
                    var rand = simplex.noise2D(xoff, yoff) * scale;
                    vertex.z = rand;
                }
            } catch(err) {
                _didIteratorError2 = true;
                _iteratorError2 = err;
            } finally {
                try {
                    if (!_iteratorNormalCompletion2 && _iterator2.
                    return != null) {
                        _iterator2.
                        return ();
                    }
                } finally {
                    if (_didIteratorError2) {
                        throw _iteratorError2;
                    }
                }
            }

            geometry.verticesNeedUpdate = true;
            cycle += speed;
        }
        
        

    
    } );
  
    
} ) ( jQuery );

The aim is to remove the middle line from the animation recreated. For more information on PlaneGeometry click here.

Answer №1

You have the ability to adjust the index of a plane geometry and then utilize it with LineSegments.

If you're interested, check out this discussion on the forum: Wireframe of quads

body{
  overflow: hidden;
  margin: 0;
}
<script type="module">
import * as THREE from "https://cdn.skypack.dev/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f08498829595b0c0dec1c3c6dec0">[email protected]</a>";
import {OrbitControls} from "https://cdn.skypack.dev/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="47332f3522220777697674716977">[email protected]</a>/examples/jsm/controls/OrbitControls";
import { ImprovedNoise } from 'https://cdn.skypack.dev/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="60140812050520504e5153564e50">[email protected]</a>/examples/jsm/math/ImprovedNoise.js';

let perlin = new ImprovedNoise()

let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 1000);
camera.position.set(0, 5, 10);
let renderer = new THREE.WebGLRenderer();
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
window.addEventListener("resize", event => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(innerWidth, innerHeight);
});

let controls = new OrbitControls(camera, renderer.domElement);

let g = new THREE.PlaneGeometry(20, 20, 50, 50);
let pos = g.attributes.position;
let uvs = g.attributes.uv;
let uv = new THREE.Vector2();
for(let i = 0; i < pos.count; i++){pos
  uv.fromBufferAttribute(uvs, i);
  uv.multiplyScalar(5);
  let z = perlin.noise(uv.x, uv.y, 0) * 3;
  pos.setZ(i, z);
}
g.rotateX(-Math.PI * 0.5);

ToQuads(g); // modify the index values

let m = new THREE.LineBasicMaterial({color: "magenta"});
let o = new THREE.LineSegments(g, m);
scene.add(o);

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

function ToQuads(g) {
  let p = g.parameters;
  let segmentsX = (g.type == "TorusBufferGeometry" ? p.tubularSegments : p.radialSegments) || p.widthSegments || p.thetaSegments || (p.points.length - 1) || 1;
  let segmentsY = (g.type == "TorusBufferGeometry" ? p.radialSegments : p.tubularSegments) || p.heightSegments || p.phiSegments || p.segments || 1;
  let indices = [];
  for (let i = 0; i < segmentsY + 1; i++) {
    let index11 = 0;
    let index12 = 0;
    for (let j = 0; j < segmentsX; j++) {
      index11 = (segmentsX + 1) * i + j;
      index12 = index11 + 1;
      let index21 = index11;
      let index22 = index11 + (segmentsX + 1);
      indices.push(index11, index12);
      if (index22 < ((segmentsX + 1) * (segmentsY + 1) - 1)) {
        indices.push(index21, index22);
      }
    }
    if ((index12 + segmentsX + 1) <= ((segmentsX + 1) * (segmentsY + 1) - 1)) {
      indices.push(index12, index12 + segmentsX + 1);
    }
  }
  g.setIndex(indices);
}
</script>

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

Vue.js: Issue with applying class binding while iterating over an object

I've been working with an object data that looks like this: object = { "2020092020-08-01":{ "value":"123", "id_number":"202009" }, "2020092020-09-01":{ "value& ...

What is the best way to transfer variables to a different page through a pop-up window?

I'm working with a function that converts the Id of the clicked element into a variable, then opens a new window with a different page. How can I access or utilize this variable on the newly opened page? var idToWrite = []; $(function(){ $(".szl ...

Do not open iframe links in a new window

Is it possible to manipulate the iframe so that links open inside the iframe window? I want the links clicked within the iframe to stay within the same window instead of opening in a new one. However, I have too many links to individually edit their code ...

The replaceWith function in jQuery does not support <script> elements

I am faced with a situation where my AJAX response includes HTML code, including <script> elements. My goal is to replace an existing element with this HTML content. However, when I attempt to do so using the following code: $(element).replaceWith( ...

Instructions on how to modify a document's content by its unique identifier using Firebase Modular SDK (V9)

I am trying to figure out how to update an existing document for the same user ID in V9 Firebase whenever they log in, rather than creating a new one each time. Any suggestions on how to achieve this? Current Code setDoc( query(collectionRef), // ...

Implementing dynamic content loading using CSS and jQuery upon link/button activation

I'm facing an issue where I am attempting to align content to the left side of my screen to display a feed while also ensuring that the pushed content is responsive. Unfortunately, the feed is not visible and the content remains unresponsive. Is ther ...

When XMLHttprequest is used to send a POST request, it sometimes

Here is the code I'm using to send a request: let ajaxHandler = new XMLHttpRequest(); ajaxHandler.onreadystatechange = function() { if(ajaxHandler.readyState == 4) { console.log(ajaxHandler.responseText); } } ajaxHandler.open("POST", ...

Issue: The error message "undefined variable 'angular'" appears when attempting to access offline files stored on a network drive

I have successfully developed offline forms using angular js v1.6.4, angular-ui-bootstrap, and angular-ui-router without the need for server hosting. When the package is saved on local storage, it functions perfectly on both IE and Chrome browsers. Howeve ...

An HTML button generated by a .js file is able to execute a .js function without any issues, but it inadvertently removes all .css styling

Currently grappling with an issue in my JavaScript self-teaching journey that I can't seem to resolve or find examples for. The problem at hand: When the HTML button calls a .js function, it successfully executes the function but also wipes out all C ...

Transfer the PointerLockControl camera view to a different camera

I am currently using the PointerLockControls to manage my camera movement. I am wondering how I can transfer the rotation of the current view to another camera in the scene that is not linked to any controls. While I am able to obtain the yawObject positio ...

The function Firebase.database() is unavailable in the Sails Service

I have developed a service named Firebase.js, and I am attempting to utilize it from my Controllers by using Firebase.database. However, I am encountering an error stating that Firebase.database() is not a function services/Firebase.js var admin = requir ...

I'm having trouble understanding why my Javascript validation suddenly stopped functioning. Can anyone assist me in troubleshooting this issue?

I have been working on this webpage for a school project for a few days, and it was running smoothly until about 10 minutes ago. The only change I made was adding an extra JavaScript validation. Now, when I try to register by clicking the "register" butt ...

Javascript datatables do not allow for setting a default column sort

I am encountering an issue where I need to sort the results by a specific column on page load. In this case, I want the initial results to be displayed in descending order based on "RecordDate". However, it seems that the server side is blocking any sort ...

Convert a two-column layout on the web into a single-column layout for mobile devices, featuring dynamic

Is there a way to style this diagram with CSS that will work on IE11 and all major browsers? It seems like Flexbox doesn't support dynamic height. Do I need separate left and right columns for larger viewports and no columns for smaller viewports? ...

Issue retrieving data from view in controller

When working with AJAX, I encountered an issue while passing a list of objects. Below is the snippet of my code: //things = JSON.stringify({ 'things': things }); var postData = { things: things }; $.ajax({ contentType: 'a ...

Using various textures on a single geometry with multiple meshes

In my code, I have a loop that generates multiple Mesh objects with different geometries, as each mesh is associated with one texture. for( var i = 0; i < voxels.length; i++ ){ texture = almacen.textPlaneTexture(voxel.texto,color,voxelSize); materi ...

Imagine a complex JSON structure with multiple levels of nesting

Take a look at this JSON data : { department_1 : [{ id : 1, name = Joe Smith, email : <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="660c150b0f120e2613150048030213">[email protected]</a>}, ...., { id : 500, name ...

Should Angular Flex Layout be considered a top choice for upcoming development projects?

Should I consider using Angular Flex Layout for upcoming projects, even though it is considered deprecated? Despite its deprecation, there are still a high number of weekly downloads on npmjs.com. I am in the process of starting a new Angular project usin ...

Tips for building a homepage button with an image and text using HTML and CSS

My ultimate goal is to create a button for the main page. I am looking to place an image and text side by side within this button, with a click on it directing me to the main page. Unfortunately, I have been facing challenges in resizing or stretching the ...

What is the process behind Stackoverflow's "Congratulations, you've earned a new badge" popup window?

Possible Duplicates: Custom notify box similar to StackOverflow Creating popup message like StackOverflow How does StackOverflow implement the "You earned a new badge" window? (the orange one that pops up at the top of the screen, I believe it&ap ...