Create a simple three-sided shape using Three.js

Currently, I am working on familiarizing myself with three.js in order to create a basic triangle. However, despite my efforts, the code I have written does not seem to be functioning properly.

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 70, window.innerWidth/window.innerHeight, 0.1, 1000 );
camera.position.z = 10;


var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

var geometry = new THREE.Geometry();
geometry.vertices= [new THREE.Vector3(2,1,0), new THREE.Vector3(1,3,0), new THREE.Vector3(3,4,0)]; 
geometry.faces = [new THREE.Face3(0,1,2)];
var mesh= new THREE.Mesh( geometry, new THREE.MeshBasicMaterial({ color: 0xffff00 }) );
scene.add(mesh);


renderer.render(scene, camera);

I'm having trouble figuring out where I went wrong with my implementation. Any advice would be greatly appreciated.

Answer №1

Creating 3D Shapes

var geom = new THREE.Geometry();
var vertex1 = new THREE.Vector3(0, 0, 0);
var vertex2 = new THREE.Vector3(30, 0, 0);
var vertex3 = new THREE.Vector3(30, 30, 0);
var triangle = new THREE.Triangle(vertex1, vertex2, vertex3);
var normalVector = triangle.normal();
geom.vertices.push(triangle.a);
geom.vertices.push(triangle.b);
geom.vertices.push(triangle.c);
geom.faces.push(new THREE.Face3(0, 1, 2, normalVector));
var mesh = new THREE.Mesh(geom, new THREE.MeshNormalMaterial());
scene.add(mesh);

Simple Outline Drawing

 var geometry = new THREE.Geometry();
geometry.vertices.push(new THREE.Vector3(-30, 2, 2));
geometry.vertices.push(new THREE.Vector3(2, 30, 2));
geometry.vertices.push(new THREE.Vector3(30, 2, 2));
geometry.vertices.push(new THREE.Vector3(-30, 2, 2));

var line = new THREE.Line(
  geometry,
  new THREE.LineBasicMaterial({ color: 0x00ff00 })
);
scene.add(line);

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

Answer №2

Isn't it interesting how challenging it was to locate an up-to-date solution? With Geometry being deprecated in recent Three.js versions, I discovered that utilizing the Shape primitive is the way to go when drawing a plane triangle.

const shape = new THREE.Shape();

const x = 0;
const y = 0;

shape.moveTo(x - 2, y - 2);
shape.lineTo(x + 2, y - 2);
shape.lineTo(x, y + 2);

const TriangleGeometry = new THREE.ShapeGeometry(shape);

Referenced from

Answer №3

When adding vertices to a face, pay attention to the order in which you add them. If the order is clockwise, the surface's normal vector will point downwards, making the triangle invisible from your camera positioned above. However, if the order is counterclockwise, the normal will face towards your camera.

To ensure visibility, consider changing:

geometry.faces = [new THREE.Face3(0,1,2)];

To:

geometry.faces = [new THREE.Face3(1,0,2)];

An additional tip is to use the 'side' argument, allowing the face material to be applied on both sides of the face.

new THREE.MeshBasicMaterial({ color: 0xffff00, side: THREE.DoubleSide };

Answer №4

This code snippet provides a solution for 2023 and can also be utilized for 3D vertex coordinates.

const points = new Float32Array([
    -1.0, -1.0, 1.0,    // representing vertex 1
    1.0, -1.0, 1.0,     // representing vertex 2
    1.0, 1.0, 1.0,      // representing vertex 3
]);

const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.BufferAttribute(points, 3));
const material = new THREE.MeshBasicMaterial({ color: 'red' });
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

Version r150

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

customize Form Modal Bootstrap with AJAX Chained Dropdown for pre-selected options

I am facing an issue with a chained dropdown on a bootstrap modal, Here is the code snippet: function changeDetail(id) { var id = id; $('#edit').prop('hidden', true); $('#modal_form').prop('hidden', fa ...

What is the best way to validate a form using JavaScript?

Recently, I completed a chess-themed hobby project using HTML, CSS, and PHP. The project allows users to view and list possible moves for a chess piece based on its type, color, and location on the board. However, the program does not take into account the ...

Setting the locale in an extended datapipe in Angular 4: A step-by-step guide

I have created a custom pipe by extending the DataPipe Angular class. import { Pipe, PipeTransform } from '@angular/core'; import { DatePipe } from '@angular/common'; @Pipe({ name: 'dateTimeFormater' }) export class DateTi ...

Renewing Firebase User Token in Angular Using HTTP Interceptor

I've encountered a puzzling issue while implementing error handling in my Angular HTTP Interceptor code. It appears that the code within my chain of ".then()" statements is being triggered out of order somehow. Here's a snippet of my code... im ...

Is there a way to showcase a PHP code snippet within JavaScript?

This piece of code contains a script that creates a new div element with a class, adds content to it using PHP shortcode, and appends it to an Instagram section. Check out the image here <script> let myDiv = document.createElement("div"); ...

The registration feature powered by JQuery is experiencing technical difficulties and not functioning

Having trouble with a registration system on my website at *. When someone registers, it should either show an error message or display "true" if the registration is successful. I have a javascript file (http://pastebin.com/mv9CWZcT) set up to redirect the ...

Is there a way for me to manage the appearance of the printed document's layout?

I have successfully added 3 print buttons to my website, each one designed to print a specific portion (div) of the webpage. Here is the code snippet for this functionality: function printPage(id) { var html="<html>"; //html+="<link rel="st ...

use d3 to dynamically color links in a react-force-graph based on their value

I'm looking to develop an app featuring a 3D Force Graph using the resources from the following project: https://github.com/vasturiano/react-force-graph You can check out my sample implementation based on the project's documentation on Github he ...

What is the best way to collapse a button in asp.net using javascript after setting it to hidden?

I have a scenario where I have 3 buttons in a row on my asp.net page. Using JavaScript, I am setting the middle button (ButtonSR) to invisible. However, I want the button below it to move up and take its place instead of leaving an empty space. ...

ng-view is the culprit behind the website's fatal error

Encountering a "RangeError: Maximum call stack size exceeded" in the console while trying to recreate a basic routing example from w3schools. The crash seems to be linked to <div ng-view></div> in index.html. Despite making minimal changes from ...

Unlimited rotation - using setInterval function

I am encountering an issue with removing the move class from my code. Can someone please check it out for me? let lis = document.querySelectorAll('li') let arr = []; for (let i = 0; i < lis.length; i++) { arr.push(lis[i]); } setInterval( ...

Return a response from the controller method without using the express response object

When attempting to handle the scenario where a fetch for an item does not return anything from another method that lacks the express response, I encounter an issue. I invoke this method from another one that has the express response: const updateItem = asy ...

Problem with JQUERY Galleria CSS positioning alignment specifically in Firefox, Chrome works without issues

I recently incorporated jquery Galleria into my website and I am currently facing an alignment issue with the div element gallery-container. Interestingly, it appears correctly aligned in Chrome but is shifted to the right in Firefox. You can view the webs ...

Managing the orientation of the print grid panel in ext.net

I have a grid panel on my webpage with a toolbar that includes a print button to print the content of the grid view. The layout direction of the grid is set from Right to Left (RTL) to accommodate Arabic text. However, when I click on the print button, th ...

Mastering advanced authentication with Passport and the JwtStrategy

During a recent project I downloaded from the internet... In one specific part of the code, the following is implemented: passport.use(new JwtStrategy({ secretOrKey: credentials.secret, jwtFromRequest: ExtractJwt.fromAuthHeader(), }, ...

Prioritizing reusability and scalability in the design of Vue.js application architecture

I am currently working on adapting an Application that was originally developed for a single country to be used in multiple countries (20+) with only slight modifications needed for each location. I am exploring ways to make the code reusable and scalable ...

Creating a query string using a jQuery array that contains multiple values for a query variable

After writing some code to convert an array into a filter string, I noticed that the generated string was not in the format I wanted. product_size=123&product_size=456 Instead of this, I needed it to be product_size=123+456. To achieve this, I reali ...

Modify route title and component if user is authenticated

I've successfully implemented a login feature in my Nativescript-Vue application that utilizes the RadSideDrawer component. My current challenge is to change the route from 'Login' to 'Logout', and I'm struggling to find a wa ...

Reorganize the layout of elements based on the array of element IDs

I have a task to complete that involves two 'ul' elements with unique id's and 'li' elements within them. <div id="sr"> <ul id="li-fav"> <li id="app-1">a</li> <li id=" ...

Is there a way to automatically retrieve CSV data using ashx on a web page?

After researching the provided links from SO without success, I decided to reach out here for help. (For privacy reasons, the actual URL and header data have been obscured) I am struggling to automate downloading data from an HTTPS web page using Delphi ...