Creating point illustrations with Three.js

Looking to incorporate random points into a web project using Three.js.

Here's the current code:

<script type="module">

  import * as THREE from 'https://threejs.org/build/three.module.js';

            import { TrackballControls } from 'https://threejs.org/examples/jsm/controls/TrackballControls.js';

            let camera, scene, renderer, controls;

            init();
            animate();

            function init() {

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

                scene = new THREE.Scene();
                scene.background = new THREE.Color( 0xffffff );

                camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 1000 );
                camera.position.set( 0, 0, 500 );

                controls = new TrackballControls( camera, renderer.domElement );
                controls.minDistance = 200;
                controls.maxDistance = 500;

                scene.add( new THREE.AmbientLight( 0x222222 ) );

                const light = new THREE.PointLight( 0xffffff );
                light.position.copy( camera.position );
                scene.add( light );

                //

                const randomPoints = [];

                for ( let i = 0; i < 10; i ++ ) {

                    randomPoints.push( new THREE.Vector3( ( i - 4.5 ) * 50, THREE.MathUtils.randFloat( - 50, 50 ), THREE.MathUtils.randFloat( - 50, 50 ) ) );

                }

                const randomSpline = new THREE.CatmullRomCurve3( randomPoints );

                //

                const extrudeSettings2 = {
                    steps: 120,
                    bevelEnabled: false,
                    extrudePath: randomSpline
                };


                const pts2 = [], numPts = 5;

                for ( let i = 0; i < numPts * 2; i ++ ) {

                    const l = i % 2 == 1 ? 10 : 10;

                    const a = i / numPts * Math.PI;

                    pts2.push( new THREE.Vector2( Math.cos( a ) * l, Math.sin( a ) * l ) );

                }

                const shape2 = new THREE.Shape( pts2 );

                const geometry2 = new THREE.ExtrudeGeometry( shape2, extrudeSettings2 );

                const material2 = new THREE.MeshLambertMaterial( { color: 0xff8000, wireframe: false } );

                const mesh2 = new THREE.Mesh( geometry2, material2 );

                scene.add( mesh2 );


                //

                const materials = [  material2 ];

                const extrudeSettings3 = {
                    depth: 40,
                    steps: 1,
                    bevelEnabled: true,
                    bevelThickness: 2,
                    bevelSize: 4,
                    bevelSegments: 1
                };

                const geometry3 = new THREE.ExtrudeGeometry( shape2, extrudeSettings3 );

                const mesh3 = new THREE.Mesh( geometry3 );

                mesh3.position.set( 150, 100, 0 );


            }

            function animate() {

                requestAnimationFrame( animate );

                controls.update();
                renderer.render( scene, camera );

            }

        </script>

Seeking guidance on how to introduce random points instead of relying solely on splines for the output. Is there a specific function or method that can be utilized for this purpose?

Your assistance would be greatly appreciated! :)

Answer №1

To begin, I suggest exploring the capabilities of ConvexGeometry. By providing an array of points or Vector3 (which it seems you have stored in the variable randomPoints), this tool can generate a shape for you.

I noticed your use of CatmullRomCurve3, which could be useful in creating curves between points. Combining these two approaches could result in a more curvaceous model.

const divisions = 25; // The number of divisions between points
const catmullPoints = new THREE.CatmullRomCurve3(randomPoints, true, "catmullrom", 0.5).getPoints(divisions);
const geometryConvex = new ConvexGeometry(randomPoints);

Now, you have a geometry with a somewhat irregular shape. However, it may appear more structured compared to the example shapes you provided. To achieve a more abstract shape, you can divide your randomPoints into chunks (i.e., multiple sub-arrays) and follow a similar approach as above. By storing the created geometries in a separate array, let's say geometries, you can then use mergeBufferGeometries to combine them into a single geometry. Here's the code:

const size = THREE.MathUtils.randInt(2, 10); // Another parameter to randomize the number of sub-arrays
const pointsChunk = chunk([...randomPoints], size); // You can use lodash or other chunk algorithms available online

const geometries = [];
for (let i = 0; i < pointsChunk.length; i++) {
    const divisions = 25;
    const catmullPoints = new THREE.CatmullRomCurve3(pointsChunk[i], true, "catmullrom", 0.5).getPoints(divisions);
    geometries.push(new ConvexGeometry(catmullPoints));
}

const mergedGeometry = BufferGeometryUtils.mergeBufferGeometries(geometries);

There are various approaches you can take, but starting with ConvexGeometry seems promising. Feel free to experiment with different methods. You can check out my attempt on this Fiddle link.

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

Use jQuery to retrieve the response from a JSON request and showcase it on the existing HTML page

Currently, I am working on a project that involves integrating a JSON-based web service from a remote server. The method of this service can be accessed by using specially formatted URLs such as: http://root-url/ws/service-name?request={json-string} The ...

The function window.scrollBy seems to be causing a conflict with jjmslideshow, resulting in the page being unable to

I wrote a simple script to create a "smooth scroll" effect when a specific link is clicked: (function() { 'use strict'; // Checking for compatibility if ( 'querySelector' in document && 'addEventListener' in window ...

Unexpected object returned by the spread operator

Currently, I am utilizing node and specifically using babel-node. "start": "nodemon --exec babel-node --presets es2015 index.js" However, I have encountered an issue with my spread syntax in the following code snippet: export const login = async (parent ...

Arranging JavaScript object by object properties (name)

Can anyone assist me with my training? I am currently learning JavaScript (Js) and TypeScript (Ts) by working with an external public API. After successfully fetching and displaying my data, I now want to implement sorting functionality. My goal is to sor ...

Encountering an error in Laravel 5.1 and Vue.js - Error code 21678: Uncaught TypeError: Unable to retrieve 'data' property from null

Recently, while working on my Laravel and Vue.js application, I encountered an issue. Everything was running smoothly until I added another component following the same procedures as before. Suddenly, the data stopped displaying in the table, and I started ...

Implement a basic JavaScript prompt feature within a Node.js application that can be integrated into

My Angular App is wrapped by electron and utilizes node.js to fetch MySQL data for AngularJs via electron. However, since there is no fixed database in my project, I have to dynamically change the database credentials from the client side, making sure it p ...

Why does one image render while the other with the same src does not?

Has anyone encountered a situation where there are 2 img tags with the same src, "images/export.png", but one displays correctly while the other doesn't? Any insights on how this discrepancy can occur? https://i.sstatic.net/z6rnW.png Here's som ...

Steps for creating a dynamic validation using a new form control

I have an item that needs to generate a form const textBox = { fontColor: 'blue', fontSize: '18', placeholder: 'email', name: 'input email', label: 'john', validation: { required: false } ...

Repairing the orientation in unique threejs capsule geometric shape

Exploring the realm of custom geometry in three.js, I decided to experiment with modifying Paul Bourke's capsule geometry example. However, as I delve into creating my own custom capsule geometry, I have encountered two main challenges: The orienta ...

Increase the progress bar at regular intervals of x seconds

I am looking for a jQuery UI progress bar that will increase by x amount every x seconds. Once it reaches 100%, I need it to trigger a function to retrieve some content. Essentially, I need a timer-like feature. EDIT: Note that I do not require any code ...

Utilizing multiple div IDs within the same script functionality

I have multiple dropdown menus on a webpage, and whenever an onchange event happens with any of these menus, I want to utilize the same block of code rather than creating individual scripts for each menu's id. This approach is preferred as the page ma ...

Switch the designation to Hover Class

I am working with nested divs and have assigned a CSS class to one of the inner divs. How can I trigger the hover effect of the class (class.hover) when the user hovers over the outer div, even if they are not directly over the inner div? I believe this m ...

Initiate a click on a radio button while also retaining the selected option when the page is

This is a unique question. In my scenario, there are two radio buttons: "radio1" and "radio2." I have successfully implemented the following actions individually: Automatically triggering a click on "radio1" upon page load. This ensures that the button ...

SOLVING the issue of page flicker in SVELTE

Within the application below, I am experiencing a peculiar page flicker effect that is often associated with AJAX requests. However, in this scenario, the cause is not AJAX-related but rather a conditional statement that triggers the rendering of different ...

Thinking of hosting an event centered around Google Maps?

Are there specific event listeners for panning or zooming the Google Map, in addition to the mouseover, mouseout, and click events? UPDATE: I tried using 'center_changed', but it didn't work the way I expected. Whenever I move the mouse ov ...

What is the best way to access a JSON Array in php without using any specified keys?

I'm dealing with a JSON object created in JavaScript and passed to PHP via AJAX. The issue I'm facing is that I can't figure out how to assign keys to each JSON object within the JSON array. Here's an example of how the JSON array looks ...

Why is my JSON object showing up as undefined in my Node.js POST request?

I have a CentOS server that is currently running a node.js HTTP server (code provided below). My goal is to pass JSON data from the command line by using the following CURL command: curl -X POST -H "application/json" -d '{"val1":"hello","val2":"my"," ...

Choose various selections from a drop-down menu using AngularJs

I am currently working on a project where I need to be able to select multiple options from a dropdown menu. The code snippet for this functionality looks like the following: //Controller $scope.data = [{id: 1, Country: Zambia}, {id: 2, Coun ...

Looking for some help with tweaking this script - it's so close to working perfectly! The images are supposed to show up while

Hey everyone, I'm struggling with a script issue! I currently have a gallery of images where the opacity is set to 0 in my CSS. I want these images to become visible when scrolling down (on view). In this script, I have specified that they should app ...

The requested resource lacks the 'Access-Control-Allow-Origin' header in a basic HTML form

Can someone help me understand why I keep encountering this error in my basic HTML form? I am attempting to display XML data on my website to showcase news stories, but unfortunately, I keep getting stuck with this persistent error. Any assistance would ...