What is the best way to create a cube in Three.js with the 4 corner points of the base and a specified height?

Given a JSON with base coordinates, I am looking to generate a cube in Three.js. The height of the cube will be a constant value, such as 1.

        {
            "points": [
                {
                    "x": 0,
                    "y": 0,
                    "z": 0
                },
                {
                    "x": 0,
                    "y": -1,
                    "z": 0
                },
                {
                    "x": 1,
                    "y": 0,
                    "z": 0
                },
                {
                    "x": 1,
                    "y": -1,
                    "z": 0
                }
            ]
        }

What type of geometry should be used in Three.js for this task?

I attempted to use ExtrudeGeometry, but encountered issues with missing top and incorrect base coordinates in the rendered cube.

Answer №1

Give this code a try:

import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

let renderer, scene, camera;

const data = {
    "points": [
        {
            "x": 0,
            "y": 0,
            "z": 0
        },
        {
            "x": 0,
            "y": -1,
            "z": 0
        },
        {
            "x": 1,
            "y": -1,
            "z": 0
        },
    {
            "x": 1,
            "y": 0,
            "z": 0
        },
    ]
};

init();
animate();

function init() {

    scene = new THREE.Scene();
    
    camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 0.1, 100 );
    camera.position.set( 5, 2, 5 );
    
    const shape = new THREE.Shape();
    
    shape.moveTo( 0, 0 ); // starting point
    
    for ( let i = 1, l = data.points.length; i < l; i ++ ) {
    
      const point = data.points[ i ];
      shape.lineTo( point.x, point.y );
    
    }
    
    const geometry = new THREE.ExtrudeGeometry( shape, { depth: 1, bevelEnabled: false } );
    geometry.center(); // optional
    const material = new THREE.MeshNormalMaterial();

    const mesh = new THREE.Mesh( geometry, material );
    scene.add( mesh );
    
    renderer = new THREE.WebGLRenderer( { antialias: true } );
    renderer.setSize( window.innerWidth, window.innerHeight );
    renderer.setPixelRatio( window.devicePixelRatio );
    document.body.appendChild( renderer.domElement );

    const controls = new OrbitControls( camera, renderer.domElement );
    
}

function animate() {

    requestAnimationFrame( animate );
    
    renderer.render( scene, camera );

}

Make sure to define the base contour in CCW order.

Check out the live demo here: https://jsfiddle.net/gmxo6td2/

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

I am encountering an issue where I am using Getserversideprops within a page to retrieve data from Strapi, but I am consistently

Having an issue with fetching data from a Strapi backend using getServerSideProps in Next.js. The data appears to be undefined, even though the link works correctly in the browser. I am fetching inside a page, not a component, following the method descri ...

Loop through an array of elements in JavaScript and retrieve the element with the largest pixel size

I am facing a challenge with elements positioned absolutely on a web page. My goal is to iterate over these elements and identify the one with the highest top value. I attempted two different approaches: const elems = document.querySelectorAll('.ind ...

The placement of the camera results in objects mysteriously vanishing

Currently, I am in the process of developing a Blazor client-side application where I need to incorporate a 3D scene. However, I am encountering a problem that seems to be related to materials. The issue arises with a composition of parallelepipeds, where ...

Can you explain how to incorporate a node module script into a React.js project?

I have encountered an issue where the element works perfectly fine when using an external node module, but fails to function properly when using a locally downloaded node module. Unfortunately, I am unable to identify the root cause of this problem. You c ...

The navigation is designed to only show up as I scroll down the page, but ideally it should be visible

I am trying to make the navigation bar appear on page load instead of when I scroll down the page. Currently, I am using this jQuery code: <script type="text/javascript> $(document).scroll(function() { if ($(this).scrollTop() == 20) { ...

Vue Single Page Application - invoking methods across all components

I am currently developing a notification feature that can be triggered from any component. It utilizes a straightforward Vuetify v-snackbar. Within App.vue <router-view :key="$route.fullPath"></router-view> <v-snackbar :valu ...

The compression feature in express.js middleware is not functioning correctly

The middlewares set up in my app are as follows: app.use(express.favicon(__dirname + '/static/public/images/favicon.ico')); app.use(express.compress()); app.use(express.json()); app.use(express.urlencoded()); app.use(express.cookieParser('S ...

Having trouble sending the welcome message?

Upon someone's entry, an error message Cannot read properties of undefined (reading 'send') is popping up in the console. I have ensured that all the necessary intents are selected for a proper welcome system or message display. Even when I ...

Tips for avoiding problems with quoting and using apostrophes in a JavaScript function inside a tag in a JSP file

Within my JSP, I have a string value stored in ${state.status.code} that I need to pass to a JavaScript function when a table element is clicked using onClick to trigger the showStatus function. Here is how I have attempted to achieve this: <c:set var= ...

Exploring VueJS: Sorting objects within an array

Currently, I am tackling a challenge in vue-js. In my codebase, there exists a data object known as items. I am iterating through these items and aiming to present a dropdown menu containing the list of products. My goal now is to showcase only those pro ...

Interactive div containing elements that cannot be clicked

http://codepen.io/anon/pen/zxoYBN To demonstrate my issue, I created a small example where there is a link button within a div that toggles another div when clicked. However, I want the link button to not trigger the toggle event and be excluded from the ...

Creating a secure authentication system with Parse for password recovery and website logins

Our organization has chosen to utilize a Parse backend for managing user accounts, and I am tasked with creating web pages for functionalities like password reset that will seamlessly integrate with our mobile applications. It has been some time since I ha ...

Error encountered: Uncaught SyntaxError - An unexpected token '<' was found while matching all routes within the Next.js middleware

I am implementing a code in the middleware.ts file to redirect users to specific pages based on their role. Here is the code snippet: import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' import { get ...

The most efficient method for distributing code between TypeScript, nodejs, and JavaScript

I am looking to create a mono repository that includes the following elements: shared: a collection of TypeScript classes that are universally applicable WebClient: a react web application in JavaScript (which requires utilizing code from the shared folde ...

Using JavaScript to auto-scroll a textarea to a certain position

Is there a way to change the cursor position in a textarea using JavaScript and automatically scroll the textarea so that the cursor is visible? I am currently using elem.selectionStart and elem.selectionEnd to move the cursor, but when it goes out of view ...

The page loads successfully at first, but upon refreshing, a 404 error occurs when using Zeit, Nextjs, and now

After recently updating from now v1 to v2, I encountered an issue where my pages would return a 404 error when reloading after pushing to production using now --prod. While everything worked fine locally with now dev, the routing seemed to be causing confu ...

Rails controller did not receive the Ajax call

I have noticed that when I make an Ajax call using jQuery, the data is always transmitted (status 200), but there are times when it's not properly received by the Rails controller. The data is sent correctly, but most of the time the controller respon ...

adjust time in jQuery AJAX request when a button is clicked

I have the following code snippet that triggers when a button is clicked. When a user clicks on a button, I want to show a progress bar or waiting image in the browser for 5 seconds. How can I set a timeout and display the progress bar or waiting image wh ...

Tips for creating a fixed element with ScrollTrigger and GSAP

How can I prevent the right div from jumping on top of the left div when using a scroll trigger to make the left div's position fixed? gsap.registerPlugin(ScrollTrigger); const tlfour = gsap.timeline({ scrollTrigger: { trigger: ".ma ...

How to retrieve a form submission from Jquery HandsonTable in PHP using $_POST

Recently, I've started diving into the world of javascript/jquery/ajax. My current project involves fetching data from a jQuery handsonTable () and integrating it with my PHP code. The process includes generating a table from a MySQL database, utili ...