Exploring sections on a Three.js Cylinder

Playing around with Cylinder Geometry from Three.js is so much fun! You can check out the documentation here.

Here's my CodePen where I've been experimenting: https://codepen.io/lklancir/pen/pdaPoY

        var gui = new dat.GUI();
        var scene = new THREE.Scene();
        var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 50 );
        camera.position.z = 30;

        var renderer = new THREE.WebGLRenderer( { antialias: true } );
        renderer.setPixelRatio( window.devicePixelRatio );
        renderer.setSize( window.innerWidth, window.innerHeight );
        renderer.setClearColor( 0x000000, 1 );
        document.body.appendChild( renderer.domElement );

        var orbit = new THREE.OrbitControls( camera, renderer.domElement );
        orbit.enableZoom = false;

        // Light setup
        var lights = [];
        lights[ 0 ] = new THREE.PointLight( 0xffffff, 1, 0 );
        lights[ 1 ] = new THREE.PointLight( 0xffffff, 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 ] );

        // Mesh setup
        var mesh = new THREE.Object3D();

        mesh.add( new THREE.LineSegments(
            new THREE.Geometry(),
            new THREE.LineBasicMaterial( {
                color: 0xffffff,
                transparent: true,
                opacity: 0.5
            } )
        ) );

        mesh.add( new THREE.Mesh(
            new THREE.Geometry(),
            new THREE.MeshPhongMaterial( {
                color: 0x156289,
                emissive: 0x072534,
                side: THREE.DoubleSide,
                flatShading: true
            } )
        ) );


 function renderMeshCylinder( mesh ) {

    var data = {
        radiusTop : 5,
        radiusBottom : 5,
        height : 30,
        radiusSegments : 60,
        heightSegments : 60,
        openEnded : true,
        thetaStart : 0,
        thetaLength : twoPi
    };

    // Function to generate geometry
    function generateGeometry() {
        updateGroupGeometry( mesh,
            new THREE.CylinderGeometry(
                data.radiusTop,
                data.radiusBottom,
                data.height,
                data.radiusSegments,
                data.heightSegments,
                data.openEnded,
                data.thetaStart,
                data.thetaLength
            )
        );
    }

    var folder = gui.addFolder( 'THREE.CylinderGeometry' );

    folder.add( data, 'radiusTop', 1, 30 ).onChange( generateGeometry );
    folder.add( data, 'radiusBottom', 1, 30 ).onChange( generateGeometry );
    folder.add( data, 'height', 1, 50 ).onChange( generateGeometry );
    folder.add( data, 'radiusSegments', 3, 64 ).step( 1 ).onChange( generateGeometry );
    folder.add( data, 'heightSegments', 1, 64 ).step( 1 ).onChange( generateGeometry );
    folder.add( data, 'openEnded' ).onChange( generateGeometry );
    folder.add( data, 'thetaStart', 0, twoPi ).onChange( generateGeometry );
    folder.add( data, 'thetaLength', 0, twoPi ).onChange( generateGeometry );

    generateGeometry();
}

renderMeshCylinder(mesh);
        var options = {};

        scene.add( mesh );

        // Rendering function
        var render = function () {
            requestAnimationFrame( render );

            if ( ! options.fixed ) {
                mesh.rotation.x += 0;
                mesh.rotation.y += 0;
            }

            renderer.render( scene, camera );

        };

        // Resize event listener
        window.addEventListener( 'resize', function () {
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
            renderer.setSize( window.innerWidth, window.innerHeight );
        }, false );

        render();

I'm currently trying to figure out how to reach a specific segment by its index or coordinate in my project. Here's a reference screenshot of what I'm aiming for:

If anyone has any guidance or suggestions on how to tackle this issue further, I would greatly appreciate it.

Answer №1

This is just a demonstration of how it can be done, utilizing THREE.Raycaster() and THREE.CylinderGeometry().

https://i.sstatic.net/jzO1b.png

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(5, 0, 10);
var renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x818181);
document.body.appendChild(renderer.domElement);

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

var mesh = new THREE.Mesh(new THREE.CylinderGeometry(2, 2, 15, 32, 20, true), new THREE.MeshBasicMaterial({
  vertexColors: THREE.FaceColors,
  wireframe: false,
  side: THREE.DoubleSide
}));
mesh.rotation.x = -Math.PI * .5;
scene.add(mesh);

var wire = new THREE.LineSegments(new THREE.WireframeGeometry(mesh.geometry), new THREE.LineBasicMaterial({
  color: "black"
}));
mesh.add(wire);

var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var intersects;
document.addEventListener("mousedown", onMouseDown, false);

function onMouseDown(event) {

  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

  raycaster.setFromCamera(mouse, camera);
  intersects = raycaster.intersectObject(mesh);

  if (intersects.length == 0) return;

  intersects[0].face.color.setHex(0xff0000);
  intersects[0].object.geometry.colorsNeedUpdate = true;
}

render();

function render() {
  requestAnimationFrame(render);
  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

display upcoming schedule and time

How can I display the future date and time in the respective field components? See below for a sample code snippet: require([ "dojo/_base/lang", "dijit/registry", "dojo/ready", "dijit/form/TimeTextBox", "dojo/parser" ], function(lang, registry, ready ...

Tips for refreshing jQuery to ensure it functions smoothly for subsequent tasks

I am facing an issue with running a second process under JQuery, as shown in the code snippet below: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <script type=" ...

What is the secret to creating a button that can sort text and another button that flips the word density in my content?

I'm not a fan of having something like this because it's displeasing to the eye: https://i.stack.imgur.com/3F4sp.jpg Instead, I prefer my word density to be more organized and structured. How can I achieve this? Sort by highest word density fi ...

I keep encountering an attach() error every time I try to close a modal that contains a vee-validated form

Every time I try to close a bootstrap modal (using bootstrap-vue) that includes a vee-validated "update" form with vue.js, I encounter the following error: main.js:477686 Uncaught (in promise) Error: [vee-validate] Validating a non-existent field: "#35". ...

Challenge encountered with Promise failing to resolve despite multiple retry attempts

I've been struggling with Promises as a beginner for the past few days. I need to make an API call and check if there is a response. If not, I have to retry calling the API a configurable number of times. I attempted the following code, but I'm u ...

Discovering an Improved Method for Implementing a Functional jQuery Menu Bar

Currently, I have a functioning Menubar where each button on the menu triggers a secondary Menubar using jQuery. The code snippet is as follows: <script> $(document).ready(function(){ $("#homeButton1").mouseover(function(){ $(".secondMen ...

Adding a contact form to a slider: A step-by-step guide

Currently, I am faced with the challenge of placing my form on a slider in such a way that the slider appears to be running in the background of the form. When using position absolute, I find myself having to apply excessive margins and top pixels due to t ...

Retrieve characters preceding and following a space (JavaScript)

In my Angular component, I have a phone number field. For example, +36 42534534534 I am trying to extract the code before the space and the phone number after the space. This is how I am currently handling it: set phoneNumberResult(value: string) { ...

TypeScript is unable to identify the property causing the error

Recently, I came across a new feature in JavaScript where you can add a cause to the Error constructor. However, when attempting to utilize this feature in my application, it fails to start due to not recognizing this additional argument in the constructo ...

Steps for embedding JavaScript code within HTML tags using a JavaScript file

Working on a React web app, I am solely using js and css files without any html. In one of my js files, there is a mix of html and js code like this: class Teams extends Component { state = { teams: [] } componentDidMount() { ...

Can someone please help me figure out why the "setInterval" function in my script isn't functioning as expected?

I've been experimenting with controlling the refresh rate of drawn objects in a canvas using JavaScript. Even after going through the tutorials and examples on w3.school, I'm still unsure why the "setInterval" function is not executing the "gener ...

Which Angular component, directive, or pipe would be best suited for creating dynamic HTML content similar to this?

(I am transitioning from React to Angular, so please bear with me if my question has a hint of React influence.) I am in need of developing an Angular component that can accept a string along with a list of terms within that string for displaying tooltips ...

Unable to retrieve text content from dynamically created element in JavaScript?

I'm currently facing an issue while working on a school project. The problem arises with a textContent error when I attempt to import a JSON file and utilize the data in a foreach loop. Despite defining the properties with elements from the JSON file, ...

What is the process for deactivating a range of dates?

I am trying to prevent users from selecting dates within the range specified by l1 and l2. However, my current method only disables the date 13. var l1 = new Date("2019-07-13"); var l2 = new Date("2019-07-30"); this.flag = 0; this.filter2 = function( ...

What is the best way to incorporate a button that, when clicked, reveals two separate images on the frontend?

describe food option heredescribe juice option hereHow can I create a button using HTML, CSS, JavaScript, and Bootstrap that displays different images for food and juices when clicked? For example, clicking on "food" will display 3 different food images, w ...

`Inefficacy of Memory Deallocation for Dynamically Added Mesh`

I am working with a Mesh instance that utilizes a TubeGeometry for its path. Whenever I make changes to the underlying curve that the TubeGeometry instance is based on, I remove the mesh from the scene and create a new one. Although the scene updates prop ...

Unexpected behavior encountered when using TypeScript type declarations

I am currently working on a Gatsby side project incorporating Typescript for the first time. I initially expected Typescript to behave similarly to PHP type declarations, but I have encountered some unforeseen issues. Despite feeling confident in my Typesc ...

Expiration Date of Third-Party Cookies

I need help retrieving the expiration date of a third-party cookie programmatically using JavaScript. Even though I can see the expiry time in the browser's DevTools (refer to the screenshot at https://i.sstatic.net/BW072.png), I am struggling to figu ...

The API call is successful, however the data is empty when returned in the callback function

Utilizing npm Express and Request modules, I am retrieving movie information through an API: var express = require("express"); var app = express(); var request = require("request"); app.get("/results", function(req, res){ console.log(getBody("http:// ...

Creating concise one-liner If statements with Handlebars: a simple guide

I am seeking clarification on the correct syntax for this code snippet: <li class="nav-item {{# if undefined !== user}} hidden {{/if}}"> My goal is to add the class name hidden only if the user variable exists. When I try implementing this, it res ...