Construct a three-dimensional structure using JavaScript and set a standard height

I'm working on developing a 3D form using code and I've encountered an issue. My plan involves storing coordinates in a vector within the same plane, with an added default height to achieve a 3D effect. However, as someone new to programming and ThreeJS, I am struggling to identify what exactly is going wrong. Can you provide any guidance or suggest an alternate method for applying default height to my 2D vector coordinates without relying on ThreeJS? Any help would be greatly appreciated! Thank you!

$(document).ready(function(){

function storeCoordinate(x, y, array) {
array.push(x);
array.push(y);
}

var coords = [];
var z=500;
storeCoordinate(3, 5, coords);
storeCoordinate(10, 100, coords);
storeCoordinate(30, 120, coords);
storeCoordinate(3, 5, coords);

for (var i = 0; i < coords.length; i+=2) {
    var x = coords[i];
    var y = coords[i+1];

    var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');

        var shape = new THREE.Shape( coords );

        ctx.moveTo(coords[i],coords[i+1]);
        ctx.lineTo(coords[i+2],coords[i+3]);
        ctx.stroke();
}


  var render,mycanvas,scene,camera,renderer,light;


    init();
    animate();
  function init(){
    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 1, 1000 );

    var extrudedGeometry = new THREE.ExtrudeGeometry(shape, {amount: 5, bevelEnabled: false});


    var extrudedMesh = new THREE.Mesh(extrudedGeometry, new THREE.MeshPhongMaterial({color: 0xff0000}));
    scene.add(extrudedMesh);


    document.body.onmousemove = function(e){
        extrudedMesh.rotation.z = e.pageX / 100;
        extrudedMesh.rotation.x = e.pageY / 100;
    }

    //lights

    dirLight = new THREE.DirectionalLight(0xffffff);
      dirLight.intensity = .9;
      dirLight.position.set(500, 140, 500);
      dirLight.castShadow = true;
      dirLight.shadowMapHeight =  2048
      dirLight.shadowMapWidth = 2048
      dirLight.shadowDarkness = .15

    spotLight = new THREE.PointLight( 0xffffff );
      spotLight.intensity = .5
      spotLight.position.set( -500, 140, -500 );
      camera.add( spotLight)
      camera.add(dirLight);


    lighthelper = new THREE.DirectionalLightHelper(dirLight, 20);
      lighthelper.children[1].material.color.set(0,0,0)
      lighthelper.visible = false;
      scene.add(lighthelper);


    ambientLight = new THREE.AmbientLight( 0x020202, 1 );
      scene.add( ambientLight );

    light = new THREE.PointLight(0xffffff);
    light.position.set(-100,200,100);
    scene.add(light);

    renderer = new THREE.WebGLRenderer({canvas: mycanvas});

    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

    controls = new THREE.OrbitControls(camera, renderer.domElement);
        controls.autoRotate = true;
        controls.enableZoom = true;
        controls.enablePan = true;
        controls.rotateSpeed = 3.0;
        controls.zoomSpeed = 1.0;
        controls.panSpeed = 2.0;
        controls.enableDamping = true;
        controls.dampingFactor = 0.25;
        controls.minDistance = 1.1;
        controls.maxDistance = 1000;
        controls.keys = [65, 83, 68]; // [ rotateKey, zoomKey, panKey ]
  }

  function animate() {
    window.requestAnimationFrame( animate );
    render();
  }

  function render() {
    renderer.render( scene, camera );
  }

  var loader = new THREE.OBJLoader();

});

Answer №1

Here is a method using the THREE.ExtrudeGeometry() function:

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

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

var grid = new THREE.GridHelper(5, 10, "white", "gray");
grid.geometry.rotateX(Math.PI * 0.5);
scene.add(grid);

var points = [
  new THREE.Vector2(0, 1),
  new THREE.Vector2(1, 1),
  new THREE.Vector2(1, 0)
]

var shape = new THREE.Shape(points);
var extrudeGeom = new THREE.ExtrudeGeometry(shape, {
  amount: 0.5,
  bevelEnabled: false
});
var mesh = new THREE.Mesh(extrudeGeom, new THREE.MeshBasicMaterial({
  color: "aqua",
  wireframe: true
}));
scene.add(mesh);

render();

function render() {
  requestAnimationFrame(render)
  renderer.render(scene, camera);
}
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/92/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

Unable to call an object that may be 'undefined': Utilizing a function with a return object that includes asynchronous functions as properties

I have a function exported in my adapter.ts file: import type { Adapter } from "@lib/core/adapters"; export default function MyAdapter (): Adapter { return { async createUser (user: User) { ... }, async findUserByEmail (email ...

Update the array state based on the selection of checkboxes and user input in real-time

In my current project using react js, I am working on a UI development task where I need to create a dynamic table based on data fetched from an API. Each row in the table includes a checkbox and a text input field that are dynamically generated. My goal i ...

Retrieving specific arrays from documents in MongoDB

[ { _id: 555, names:['John','Doe','David'] }, { _id: 625, names:['David','Mark','Carl'] }, { _id: 299, names:['Bill','Carlos','Ventus&apo ...

Attention: Issue with 'className did not match' error in react-material-ui-carousel

I am currently utilizing React, NextJS, and Material UI in my project I recently integrated the react-material-ui-carousel package, but encountered the following error: Warning: Prop className did not match. Server: "MuiButtonBase-root MuiIconButton ...

Looking to parse JSON data using jQuery?

I need assistance with the syntax to parse this json data from the server using jQuery. Despite trying various examples from different sources, I am consistently receiving 'undefined' as the output instead of the expected ID numbers. Each ID numb ...

Unable to load new page using Selenium and Chromedriver

Currently, I am in the process of learning how to utilize Selenium with Python. As a beginner exercise, I have been attempting to click a button on a webpage. Although I have been able to successfully locate the button and click on it, an unusual issue ari ...

Nested iteration using a for loop in Javascript

I am attempting to iterate through a large array of values and calculate the average of one of the values for each second. I seem to be having trouble getting this code to function correctly, and it appears that the issue lies within the nested while loop. ...

I cannot seem to locate the module npm file

Currently, I am in the process of following a Pluralsight tutorial. The instructor instructed to type 'npm install' on the terminal which resulted in the installation of a file named npm module in the specified folder. However, when I attempted t ...

I am struggling to make my button hover effects to function properly despite trying out numerous suggestions to fix it

As a newcomer, this is my first real assignment. I've managed to tackle other challenges successfully, but this one seems a bit more complex and I'm struggling to pinpoint where I'm going wrong. Despite googling various solutions, none of th ...

Distinguishing Between server.listen() and app.listen() in Google Apple Engine

I am currently working on a NodeJS + Express application. While running it locally, I have the following code: const port = 3001; server.listen(port, () => { console.log(`App listening on port ${port}`); }); However, when deploying to GAE, I switch ...

What could be causing the unexpected behavior of angular.isNumber()?

I'm encountering an issue with AngularJS's angular.isNumber, as it doesn't seem to work with strings that represent numbers. Is there a mistake on my end? Would utilizing isNaN() be a better approach? angular.isNumber('95.55') == ...

iOS now supports fully transparent tooltips and modals, offering a sleek and

I am currently working on developing tooltips and modals for an iOS app using react-native. The problem I am encountering is that the background of the tooltips and modals is not transparent, although it appears correctly on the Android version of the app. ...

Stop the background from scrolling and prevent auto-jumping to the top on mobile devices

When users click on the hamburger icon in the top right of our mobile site, I want the drop-down menu to appear and be scrollable without the background scrolling. I tried using JavaScript to set the body to fixed when the menu icon is clicked, but this ca ...

What is the best way to modify a data parameter in Angular 2?

I am facing an issue while trying to change a data parameter in my component file: this.commandList.ListesCommandesATransmettre.forEach(data => { this.catalogs.forEach(catalog => { if (catalog.Libelle === data.Catalogue) { if ...

When is it more advantageous to use Next.js instead of plain React?

As someone who is new to the world of React, I've dabbled in creating simple web applications using the React library and the convenient create-react-app command with npx. However, I've come to realize that the Client Side Render (CSR) applicatio ...

Having trouble with your JavaScript regex not functioning properly?

I am currently working with an array of arrays and I need to iterate through it to retrieve each word, excluding any "@", punctuation, and hashtags. However, my regular expression seems to be removing certain words entirely from the array and I can't ...

What strategies can be used to scale up a website's images in proportion to their page views or traffic?

The situation: On my simple HTML website, I have a group of images placed side by side. Each image is connected to a specific article, and when you hover over the image, a detailed description of the linked article pops up in the center of the page. The o ...

The mesh Lambert material creates an odd appearance when combined with lighting effects

Having trouble with Mesh Lambert Material in Three.js. I've created a plane with varying height points, but when applying light, the higher points appear darker when they should be brighter. Here's a snippet of my code: const geometry = new THRE ...

Expand and collapse divs using jQuery when a JavaScript do_PostBack link is clicked

Currently, I am in the process of developing a website called TheDigitalScale. One particular feature on the site involves using jQuery to create an expanding div that opens when clicked and closes with another click. <script type="text/javascript"> ...

Utilize JavaScript destructuring to assign values to a fresh object

When working with JavaScript/Typescript code, what is a concise way to destructure an object and then assign selected properties to a new object? const data: MyData = { x: 1, y: 2, z: 3, p: 4, q: 5 } // Destructuring const { x, z, q } = data; // New O ...