Struggling to generate a Cylinder using three.js

I've been attempting to produce a Cylinder, but unfortunately without any luck. Here's the code I used:

geometry02 = new THREE.CylinderGeometry( 20, 100, 100, 1000 );
material02 = new THREE.MeshBasicMaterial({color: 0x0000ff});
cylinder02 = new THREE.Mesh( geometry02, material02 );
cylinder02.position.x = 300;
scene.addObject( cylinder02 );

Could it be that I missed out on including something?

Answer №1

Just wanted to let you know that the code snippet you shared is working perfectly fine. I tested it with an example and everything looks good.

A few things to check:

  1. Ensure there are no javascript errors (check your browser's Console for any issues)
  2. Make sure the camera is correctly positioned towards your object (try using camera.lookAt(yourObject);)
  3. Check if your model's position/scale values are suitable and within the camera's visible area

On a side note, consider lowering the segmentsRadius parameter (currently set at 1000) to achieve a similar level of detail with fewer vertices/faces.

Answer №2

Check out the code snippet below:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>3d cylinder</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
        <style>
            body {
                font-family: Monospace;
                background-color: #f0f0f0;
                margin: 0px;
                overflow: hidden;
            }
        </style>
    </head>
    <body>

        <script src="three.min.js" type="text/javascript"></script>
        <script src="Stats.js" type="text/javascript"></script>
        <script src="Detector.js" type="text/javascript"></script>

        <script>
            if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

            var container, stats;

            var camera, scene, renderer, light;

            var cylinder, line, geometry;

            var targetRotation = 0;
            var targetRotationOnMouseDown = 0;

            var mouseX = 0;
            var mouseXOnMouseDown = 0;

            var windowHalfX = window.innerWidth / 2;
            var windowHalfY = window.innerHeight / 2;

            init();                     
            animate();

            function init() {

                container = document.createElement( 'div' );
                document.body.appendChild( container );

                var info = document.createElement( 'div' );
                info.style.position = 'absolute';
                info.style.top = '10px';
                info.style.width = '100%';
                info.style.textAlign = 'center';
                //info.innerHTML = 'Drag to spin the cylinder';
                container.appendChild( info );

                // camera

                camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 20000 );
            camera.position.y = 100;
            camera.position.z = 800;

                // scene

                scene = new THREE.Scene();

                // light

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

                light = new THREE.DirectionalLight( 0xffffff );
                light.position.set( 0, 1, 0 );
                scene.add( light );

                // texture

                var map = THREE.ImageUtils.loadTexture( 'ash_uvgrid01.jpg' );
                map.wrapS = map.wrapT = THREE.RepeatWrapping;
                map.anisotropy = 16;

                materials = [
                    new THREE.MeshLambertMaterial( { ambient: 0xbbbbbb, map: map, side: THREE.DoubleSide } ),
                    new THREE.MeshBasicMaterial( { color: 0xffffff, wireframe: true, transparent: true, opacity: 0.1, side:                                     THREE.DoubleSide } )
                ];

                // Grid

                geometry = new THREE.Geometry();
                geometry.vertices.push( new THREE.Vector3( - 500, 0, 0 ) );
                geometry.vertices.push( new THREE.Vector3( 500, 0, 0 ) );

                for ( var i = 0; i <= 20; i ++ ) {

                    line = new THREE.Line( geometry, new THREE.LineBasicMaterial( { color: 0x000000, opacity: 0.2 } ) );
                    line.position.z = ( i * 50 ) - 500;
                    scene.add( line );

                    line = new THREE.Line( geometry, new THREE.LineBasicMaterial( { color: 0x000000, opacity: 0.2 } ) );
                    line.position.x = ( i * 50 ) - 500;
                    line.rotation.y = 90 * Math.PI / 180;
                    scene.add( line );

                }

                // cylinder

                cylinder = THREE.SceneUtils.createMultiMaterialObject( new THREE.CylinderGeometry( 50, 50, 200, 25, 10, false ), materials );
                cylinder.overdraw = true;
                scene.add(cylinder);


                // renderer

                renderer = new THREE.CanvasRenderer();
                renderer.setSize( window.innerWidth, window.innerHeight );
                container.appendChild( renderer.domElement );               

                /* stats */

                stats = new Stats();
                stats.domElement.style.position = 'absolute';
                stats.domElement.style.top = '0px';
                container.appendChild( stats.domElement );

                document.addEventListener( 'mousedown', onDocumentMouseDown, false );
                document.addEventListener( 'touchstart', onDocumentTouchStart, false );
                document.addEventListener( 'touchmove', onDocumentTouchMove, false );               

                window.addEventListener( 'resize', onWindowResize, false );

            }

            function onWindowResize() {

                camera.left = window.innerWidth / - 2;
                camera.right = window.innerWidth / 2;
                camera.top = window.innerHeight / 2;
                camera.bottom = window.innerHeight / - 2;
                camera.aspect = window.innerWidth / window.innerHeight;
                camera.updateProjectionMatrix();

                renderer.setSize( window.innerWidth, window.innerHeight );

            }

            function onDocumentMouseDown( event ) {

                event.preventDefault();

                document.addEventListener( 'mousemove', onDocumentMouseMove, false );
                document.addEventListener( 'mouseup', onDocumentMouseUp, false );
                document.addEventListener( 'mouseout', onDocumentMouseOut, false );

                mouseXOnMouseDown = event.clientX - windowHalfX;
                targetRotationOnMouseDown = targetRotation;

            }

            function onDocumentMouseMove( event ) {

                mouseX = event.clientX - windowHalfX;

                targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.02;

            }

            function onDocumentMouseUp( event ) {

                document.removeEventListener( 'mousemove', onDocumentMouseMove, false );
                document.removeEventListener( 'mouseup', onDocumentMouseUp, false );
                document.removeEventListener( 'mouseout', onDocumentMouseOut, false );

            }

            function onDocumentMouseOut( event ) {

                document.removeEventListener( 'mousemove', onDocumentMouseMove, false );
                document.removeEventListener( 'mouseup', onDocumentMouseUp, false );
                document.removeEventListener( 'mouseout', onDocumentMouseOut, false );

            }

            function onDocumentTouchStart( event ) {

                if ( event.touches.length === 1 ) {

                    event.preventDefault();

                    mouseXOnMouseDown = event.touches[ 0 ].pageX - windowHalfX;
                    targetRotationOnMouseDown = targetRotation;

                }

            }

            function onDocumentTouchMove( event ) {
                if ( event.touches.length === 1 ) {
                    event.preventDefault();
                    mouseX = event.touches[ 0 ].pageX - windowHalfX;
                    targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.05;
                }
            }

            function animate() {
                requestAnimationFrame( animate );
                render();
                stats.update();

            }

            function render() {             
                cylinder.rotation.y += ( targetRotation - cylinder.rotation.y ) * 0.05;
                renderer.render( scene, camera );               
            }           


        </script>

    </body>
</html>

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

How to adjust animation timing for various elements during a CSS 3D flip with a delay?

Here is a CSS flip setup that I have been working on in this fiddle: http://jsfiddle.net/6r82fzk6/ The Goal: I am trying to achieve a slower transition for the back element compared to everything else. The idea is to have the child element of the back fac ...

Looking to locate a specific video within the DOM

Is there a way to detect the presence of video content in the DOM, regardless of how it is inserted? I attempted using phantomJS but was unable to find a satisfactory method. ...

Trouble with X-editable linking to database for updates

Utilizing the X-Editable plugin within my PHP application to update fields in a table and utilizing a POST file to update the database. Below is the form code: <table id="restaurant" class="table table-bordered table-striped"> <tbody> ...

What is the process for defining the type of the context for an Apollo resolver?

I am facing an issue with my Apollo GraphQL subgraph where I need to define the type for the context argument in my resolvers. When creating a resolver, I tried setting the context type like this: interface Context { dataSources: { shopify: Shopify; ...

What is the reason behind arr.reverse() flipping the original array?

My goal is to reverse an array and store the reversed version in a new array without altering the original array. Here is the code I am using: var arr= ["1", "2", "5"] var arrTwo = arr.reverse(); console.log(arrTwo) \\ ["5" , "2" , "1"] console. ...

Showcase Pictures from a Document

Is there a way to upload an image via an input field and display it? I want to showcase a profile picture that can be saved in a database. The process should be simple for the user, with the ability to easily upload and view the image. function Save() { ...

Display or Conceal Sub-Header according to Scrolling Position

Question: My goal is to create a specific animation on my website. When loading the page on mobile, I want to display the div with ID "sub-header", but once the user scrolls more than 50px down, I want to hide it. Additionally, if the user scrolls up by 60 ...

What is the best method for choosing visible elements within a scrollable container?

Is there a way to retrieve the list of visible elements within a scrollable container? The number of elements that are visible on the screen changes as one scrolls, making it challenging to add a specific class to only the last two visible elements. Any s ...

Implementing a post request triggered by a button click in Node.js with Express

How can I invoke a controller from a button click event? I tested it in Postman and it works fine, but I'm having trouble calling it from a button on my front-end. I am using Nodemailer and Node Express to send emails. Here is my code. Can someone p ...

Flawless Carousel - Flipping the Sequence

I am currently implementing Slick Carousel on a website that I am working on. One challenge I am encountering is trying to get the "slider-nav" to move in the opposite direction than it normally does. For instance, at the moment, the order goes like this ...

Reveal/Conceal footer upon vertical scrolling

I am attempting to achieve the following goals: Display the div element when the scrolling position is greater than 20 Apply a fadeOut effect after a certain delay Prevent the fadeOut effect when hovering over the sticky footer This is my implementation ...

Desktop Safari displays Font-awesome icons with trimmed corners using a border-radius of 50%

While working on incorporating font awesome share icons into my project, I encountered an issue with getting a circle around them. After exploring various approaches, I opted for a CSS solution. Using React FontAwesome posed some challenges that led me to ...

How to alter row colors in SQL/PHP tables

echo "<tbody"; echo "<tr>"; echo "<td>{$id}</td>";// display customer Id echo "<td> {$firstname} {$lastname}</td>"; //display customer title,firstname,lastname echo "<td>{$date->format('h:i A')}</td> ...

The logo marquee unexpectedly bounces up and down at the end of every

Struggling with a JavaScript code issue. The Logo marquee suddenly jumps at the end of each loop: I've tried everything, but I can't seem to fix it and make it work as intended Here's the complete script that technically works, but causes ...

The FullCalendar plugin on the list was experiencing functionality issues

I came across this code snippet that is causing me some trouble: .... import { FullCalendarComponent } from '@fullcalendar/angular'; import { EventInput } from '@fullcalendar/core'; import dayGridPlugin from '@fullcalendar/daygrid& ...

Is it possible to set up a server with 'app' as the designated request handler?

When working with NodeJS, server creation can be done simply by using: http.createServer(function(req,res) { /* header etc. */}); However, as I delved into using express, the server was automatically created for me. Moving on to learning about sockets, I ...

Tips for utilizing Selenium to acquire links from a webpage

Is it possible to retrieve the link location of a web element in Selenium? While we can easily obtain the text from a web element and use getAttribute("href") method to get the location of a hyperlink, my need is to extract all the links present. For insta ...

Is there a simple method to automatically increase the version number of Mongoose documents with each update request?

I'm eager to utilize Mongooses document versioning feature with the "__v" key. Initially, I struggled with incrementing the version value until I learned that adding this.increment() when executing a query is necessary. Is there a method to have this ...

Setting up the data for the AjaxAppender Request Log4Javascript

I am completely new to Log4Javascript and the concept of logging, so please bear with me. My current task involves sending logs to a CouchDB server using a POST request. However, I keep encountering an error from the server: {"error":"bad_request","reaso ...

Encountering an error message when trying to launch an application: Module

Every time I try to launch my react-native app in git-bash, I encounter the following error message. I have already uninstalled and reinstalled node.js, cleared the cache, and attempted various solutions from Stack Overflow and GitHub with no success. ...