Adjust the dimensions of a Three.js-generated 3D Cylinder in real-time

Is it possible to dynamically change the dimensions of a 3D cylinder created using Three.js, similar to how we can adjust the size of a cube in this live example: http://jsfiddle.net/EtSf3/4/

Below is the code I have for the cylinder:

HTML:

<script src="http://www.html5canvastutorials.com/libraries/three.min.js"></script>
<div id="container"></div>

JS

//Script for 3D Cylinder 

// revolutions per second
var angularSpeed = 0.2;
var lastTime = 0;

var cylinder = null;
// this function is executed on each animation frame
function animate() {
    // update
    var time = (new Date()).getTime();
    var timeDiff = time - lastTime;
    var angleChange = angularSpeed * timeDiff * 2 * Math.PI / 1000;
    cylinder.rotation.x += angleChange;
    cylinder.rotation.z += angleChange;
    lastTime = time;

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

    // request new frame
    requestAnimationFrame(function () {
        animate();
    });
}

// renderer
var container = document.getElementById("container");
var renderer = new THREE.WebGLRenderer();
renderer.setSize(container.offsetWidth, container.offsetHeight);
container.appendChild(renderer.domElement);

// camera
var camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.z = 700;

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

// cylinder
// API: THREE.CylinderGeometry(bottomRadius, topRadius, height, segmentsRadius, segmentsHeight)
cylinder = new THREE.Mesh(new THREE.CylinderGeometry(150, 150, 500, 100, 100, false), new THREE.MeshPhongMaterial({
    // light
    specular: '#cccccc',
    // intermediate
    color: '#666666',
    // dark
    emissive: '#444444',
    shininess: 100
}));
cylinder.overdraw = true;
cylinder.rotation.x = Math.PI * 0.2;
//cylinder.rotation.y = Math.PI * 0.5;
scene.add(cylinder);

// add subtle ambient lighting
var ambientLight = new THREE.AmbientLight(0x444444);
scene.add(ambientLight);

// directional lighting
var directionalLight = new THREE.DirectionalLight(0xcccccc);
directionalLight.position.set(1, 1, 1).normalize();
scene.add(directionalLight);

// initiate animation
animate();

Here is the corresponding Fiddle: http://jsfiddle.net/dpPjD/

If you require further information or have any suggestions, feel free to reach out.

Answer №1

After incorporating the object geometry into the mesh, it undergoes a conversion process to be represented as face/vertex/UV/normals and becomes an integral part of the mesh structure. Take for instance the cylinder shape that has been specified; it gets tessellated (divided) by Three.js into triangles with a vertex count exceeding 10,000.

Therefore, even though global mesh properties such as transforms can be updated, modifying individual geometries is almost equivalent to generating a brand new geometry during each animation frame. If you have detailed knowledge of the vertices that require modification, you can directly update them using the geometry.vertices property. However, if you are not aware of this information, I'm afraid there might not be a straightforward solution available.

Answer №2

If you want to replace the geometry of an object, you can achieve it by using the following code snippet:

cylinder.geometry.dispose();
cylinder.geometry = new THREE.CylinderGeometry(updatedBottomRadius, updatedTopRadius, updatedHeight, 32);

Here, updatedBottomRadius, updatedTopRadius, and updatedHeight represent the new dimensions either from a set value or a variable that changes dynamically, especially if you intend to manipulate the cylinder's height.

The dispose method ensures that the previous geometry of the object is removed before applying the new geometry.

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

Next.js is refusing to render an array of HTML elements

Consider this scenario where I have a block of code in TypeScript that attempts to create and display a list of elements. Here is a sample implementation: const MenuList = ():ReactElement => { const router = useRouter(), liElements:any = []; con ...

What is causing the warnings for a functional TypeScript multidimensional array?

I have an array of individuals stored in a nested associative array structure. Each individual is assigned to a specific location, and each location is associated with a particular timezone. Here is how I have defined my variables: interface AssociativeArr ...

The jQuery application adds new HTML elements to the page and then reveals the code that follows

When making an Ajax call and rendering two templates based on the response, I encountered a problem where the correct template renders but the script following it appears on the page as plain text. Here's the code snippet with the issue: if (question ...

Experiencing a snag with implementing Firebase version 9 FCM in Next.js 12

I decided to incorporate push notifications into my Next.js (version 12) app, so I integrated Firebase Cloud Messaging. Here is the implementation: import { initializeApp, getApp, getApps } from "firebase/app" import { getMessaging, getToken } fr ...

Creating a tree structure from a one-dimensional array with the help of dual data tables in JavaScript

I'm struggling to create a tree structure from a flat array using two Mock data tables in JSON. The table should match the unique IDs to determine the hierarchy between them. JSON with Groups DB array example: { "group": [ { "groupName" ...

Tips on including starting information into an angularjs application from the displayed HTML

I'm currently working on a complex AngularJs application that requires User Login. Once the user is authenticated, a page will be displayed to them and additional data will be loaded later. There are two methods for achieving this: XHR Fetch af ...

What steps are needed to switch colors after a loop has been clicked?

I have a loop setup like this: data: { show: false } .test { hight: 10px; background-color: red; } .test2 { hight: 15px; } <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div v-for="value in da ...

Tips for navigating through complex JSON structures with JavaScript or JQuery

I'm currently navigating the complexities of parsing a multi-level JSON array as a newcomer to JSON. I am seeking solutions using either JavaScript or jQuery. My goal is to extract the application id, application description, and Product description f ...

Can you tell me if the "dom model" concept belongs to the realm of HTML or JavaScript?

Is the ability to use "document.X" in JavaScript to visit an HTML page and all its tags defined by the HTML protocol or the ECMAScript protocol? Or is it simply a choice made in the implementation of JavaScript, resulting in slight differences in every bro ...

The Reactjs dependency tree could not be resolved

In my current project, I've been attempting to integrate react-tinder-card. After running the command: npm install --save react-tinder-card I encountered this error in my console: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency ...

Error encountered: expected application router to be connected

I encountered an error while trying to migrate from next 12 to next 13 on my old project. Check out the Console Error Log Despite looking for faults in my code, I couldn't find any reason for these errors. Even after extensive Googling, no solution ...

What are some strategies to prevent django form fields from being reset or cleared in the event of an error during submission?

I'm utilizing django's registration-redux for user registration, but I'm facing an issue. When I enter the same user ID, it displays an error and clears all the input fields on the form. How can I prevent this error from occurring without cl ...

"Utilizing Vue.js to dynamically fill input fields based on the selection of an element

As I am still new to learning Vue.js, I may not be using the correct terminology here. My current project involves a basic Vue application where I have implemented a simple search box functionality. The search box triggers an event (v-on:blur) when text i ...

Creating a ListView in React Native and utilizing the CloneWithRow method with an object instead of an

When retrieving data from a webservice, I am able to work with JSON arrays without any issues. WebServiceHandler.get('http:/api.local/stock',{},{) .then((val)=>{ this.setState({ dataSource: this.state.dataSou ...

Issues encountered with asp.net javascript function not executing

Having trouble getting a javascript function to execute via jquery in an asp.net setting. Despite trying various approaches, the function doesn't run upon clicking the button. I've experimented with omitting jquery and using a static html input c ...

The repository's dependencies remain unresolved by Nest

I encountered an error in my nestjs application. Unfortunately, I am having trouble identifying the issue within my code snippet. Here is a glimpse of the relevant sections: AppModule import { Module } from '@nestjs/common'; import { TypeOrmMod ...

Exploring the differences between selecting an element by its class and making multiple calls to select elements

I have a question about choosing multiple elements from a page. Is it better to use a selector by class, or make multiple calls using the selector by id? The number of elements I want to select, or unwanted elements that need to be checked by the selector ...

Refreshing web pages using AJAX

I currently have an application that includes a search feature where users can look up items in the database. The search functionality is working well with AJAX, but I'm now looking to incorporate this AJAX functionality into my pagination system. Spe ...

Unable to pass an event parameter using my this.handleChange function in react-native

Encountering an issue with the error message "undefined is not an object (evaluating 'event.preventDefault)" It appears that I am unable to pass an event parameter to the handleChange function in my child component, which is being rendered in the par ...

Unable to reach the sub-component of the JSON object that was returned

For some reason, I can't seem to access a sub object of a returned $Resource object that fetched a group of JSON objects. It's baffling me. Resource > $resolved: true > $then: function (b, g) {var j=e(),h= > data: Object > 519bc5f6 ...