Tips for creating a wavy surface on a cylinder using three.js (with images)

I've been working on giving my cylinder geometry a wavy surface, aiming for a look like this: https://i.sstatic.net/aCaV7.png

However, after implementing the following code, it ended up looking quite distorted as shown in these images: https://i.sstatic.net/7dxVN.png and here from a different angle: https://i.sstatic.net/jWzXJ.png

The approach I took was iterating through all the vertices and applying the sine function to them like so:

STC.WarpControls.prototype.waves = function(){
    var geometry = this.threeDHandler.threeD_meshes[0].geometry;
    for (let i = 0; i < geometry.vertices.length; i++) {
        geometry.vertices[i].y = Math.sin(( i + 0.00002)) * (geometry.vertices[i].y);
    }
    geometry.verticesNeedUpdate = true;
}

I'm puzzled by why my shape turned out weird. Can anyone shed some light on what might have caused this distortion and provide insights into achieving a wavy shape on a cylinder? Your help is greatly appreciated!

Answer №1

If you want to determine the outcome of a sine function for a vertex with a Y-coordinate, here's one way to do so:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 0, 6);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

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

var cylinderGeom = new THREE.CylinderGeometry(1, 1, 4, 16, 20, true);

var vec3 = new THREE.Vector3(); // temporary vector
cylinderGeom.vertices.forEach(v => {
  vec3.copy(v); // copy the current vertex to the temporary vector
  vec3.setY(0); // keep x and z values (making the vector parallel to the XZ plane)
  vec3.normalize(); // normalize the vector
  vec3.multiplyScalar(Math.sin(v.y * Math.PI) * 0.25); // multiply it by the sin function
  v.add(vec3); // add the temporary vector back to the current vertex
});
cylinderGeom.computeVertexNormals();

var cylinder = new THREE.Mesh(cylinderGeom, new THREE.MeshNormalMaterial({
  side: THREE.DoubleSide
}));
scene.add(cylinder);

renderer.setAnimationLoop(() => {
  renderer.render(scene, camera);
})
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://threejs.org./build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></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

Instructions for separating a string into smaller parts, further splitting one of the resulting parts along with another associated value, and then combining the leftover segments with the remaining parts

My goal is to work with a string that is between 2000 and 3000 characters long, containing over a hundred non-uniformly placed \n characters. I want to divide this string into segments of 1000 characters each. In the resulting array of strings, I want ...

Detecting the existence of a scrollbar within the document object model using JavaScript - a guide

Could someone provide a JavaScript syntax for detecting the presence of a scrollbar in the DOM by measuring the body height and window height? ...

JavaScript Equivalent to C#'s BinaryReader.ReadString() Function

Currently, I am in the process of translating C# code into JavaScript. While transferring multiple datatypes from this file to matching functionalities found in various JavaScript libraries was relatively smooth, there is one specific function that seems t ...

Promise rejection not handled: Trying to modify headers after they have already been sent to the client

I can't seem to figure out why these errors keep popping up. I've tried looking for solutions online but haven't had any luck. Here is the node function I'm using for an API call: exports.GetEmployeeConfirmationList = function (req, res ...

Organize data in a table using a dropdown selection menu

My data structure looks like this: $scope.friends = [ { name:'John', phone:'555-1212', age:10 }, { name:'Mary', phone:'555-9876', age:19 }, { name:'Mike', phone:'555-4321', age:21 }, { na ...

establish the data type for the key values when using Object.entries in TypeScript

Task Description: I have a set of different areas that need to undergo processing based on their type using the function areaProcessor. Specifically, only areas classified as 'toCreate' or 'toRemove' should be processed. type AreaType ...

React's memo and/or useCallback functions are not functioning as anticipated

Within my Home Component, there is a state called records, which I utilize to execute a records.map() and display individual RecordItem components within a table. function Home() { const [records, setRecords] = useState<Array<RecordType>>(l ...

Is there a way to represent this specific #define in webgl?

Currently, I am experimenting with a shader that entails the following statement: #define SHADER_NAME MeshDepthMaterial My objective is to avoid redeclaration of something: #if SHADER_NAME != MeshDepthMaterial varying vec2 foo; #endif However, I am ...

The attribute 'subtle' is not found within the definition of 'webcrypto' type

Currently, I am working with Node v17.4 and I am looking to utilize the webcrypto API. Referencing this specific example, I am attempting to include subtle in my project, but TypeScript is throwing an error: Property 'subtle' does not exist on ...

Manipulate the value of an HTML element's style parameter with jQuery

How do I change an element's style property using jQuery? This is the HTML code I am working with: <div id="template" style="width:200px; height:200px; border:none;">blabla...</div> I attempted to do this: $('#template').attr ...

What is the most efficient way to generate a pug file with a hashed resource name using Webpack 2.0?

Here is how my file structure looks: /public (files ignored by git) /src index.js /views index.pug server.js webpack.config.js index.pug <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link href="/publi ...

Struggling to make AngularJS routes function properly

After starting from scratch, I rebuilt it with freshly downloaded angularJS (version 1.5.8). I simply placed both angular.js and angular-route.js in the library folder following this setup: https://gyazo.com/311679bf07249109671d621bc89d2d52 Here is how in ...

Retrieve an item from an array using AJAX

I am working on a function using ajax that retrieves a set of values: $.each(data.dataa, function (i,item) { $.each(item, function (index, dat) { $str+=dat; }) $ulSub.append( '<li id="'+item.id +'" class="ui-widget-c ...

Refreshing image does not reload

function updateimage(){ $("#fileimg").attr("src","path/to/image.jpg"); $('#fileimg').fadeIn('slow'); setTimeout(updateimage, 5000); } Greetings, I am trying to refresh an image every 5 seconds but it's not working as ...

Switching to '@mui/material' results in the components failing to render

I have a JavaScript file (react) that is structured like this: import { Grid, TextField, makeStyles } from '@material-ui/core' import React from 'react' import {useState} from 'react' //remove this function and refresh. see ...

How do I resolve the jQuery error "unable to find function url.indexOf" when working with Vide?

I had previously asked a question regarding the use of the Vide plugin for playing background videos on my website, which can be found here. However, I am now encountering an error that is puzzling me: https://i.stack.imgur.com/UDFuU.png I am unsure abo ...

Enhancing x-axis presentation in D3.js-generated charts

I created a bar chart using D3.js, but I have encountered an issue with one of the values on the x-axis being too long. I attempted to use CSS properties like text-overflow: ellipsis, width: 10px, and overflow: hidden to abbreviate values that exceed a cer ...

The error encountered is due to an invalid assignment on the left-hand side

I'm encountering the error below: Uncaught ReferenceError: Invalid left-hand side in assignment This is the problematic code: if (!oPrismaticMaterial = "") { for (var i = 0; i < oPrismaticMaterial.length; i++) { if (oPrismaticMater ...

The issue of linking .then() functions

I've been struggling to grasp the concept of Promises/then-ables for a while now. Currently, I am working with NextJS. My goal is to chain together the following steps: Retrieve data from an API Save the data Modify the data to create a component (w ...

Gridsome server-side rendering encounters issues with Auth0 authentication when the window object is not defined

After successfully following the Auth0 Vuejs tutorial with Gridsome during development, I encountered a problem when trying to build using gridsome build. The build failed because window was undefined in a server context. I discovered some issues in the A ...