Three.js - Placing 2D elements within a 3D environment using Vertices

Looking for advice on drawing a face in 3D Space using an array of 3D Points. How can I achieve this? Essentially, I want to create a flat object in a 3D environment.

My current approach involves connecting points Points[0] to Points[1], Points[1] to Points[2], and so on.

Here is the code snippet I am currently using:

var geometry = new THREE.BufferGeometry();

var vertices = faceToTriangles(VerticesArray);  // custom function

var uvs = new Float32Array([
    0.0, 0.0,
    1.0, 0.0,
    1.0, 1.0,

    0.0, 0.0,
    1.0, 1.0,
    0.0, 1.0
]);


geometry.addAttribute('position', new THREE.BufferAttribute(vertices, 3));
geometry.addAttribute('uv', new THREE.BufferAttribute(uvs, 2));
var material = new THREE.MeshLambertMaterial({ color: 'red' });
material.side = THREE.DoubleSide;
var mesh = new THREE.Mesh(geometry, material);

The custom function used:

function faceToTriangles(VerticesArray) {
    var Triangles = new Float32Array((VerticesArray.length - 2) * 9);

    var i = 0;
    for ($v = 1; $v < Face.Vertices3D.length - 1; $v++) {
        Triangles[i++] = parseFloat(Face.Vertices3D[0].x);
        Triangles[i++] = parseFloat(Face.Vertices3D[0].y);
        Triangles[i++] = parseFloat(Face.Vertices3D[0].z);

        Triangles[i++] = parseFloat(Face.Vertices3D[$v].x);
        Triangles[i++] = parseFloat(Face.Vertices3D[$v].y);
        Triangles[i++] = parseFloat(Face.Vertices3D[$v].z);


        Triangles[i++] = parseFloat(Face.Vertices3D[$v + 1].x);
        Triangles[i++] = parseFloat(Face.Vertices3D[$v + 1].y);
        Triangles[i++] = parseFloat(Face.Vertices3D[$v + 1].z);
    }

    return Triangles;
}

While this function works well in most scenarios, it sometimes generates inaccuracies where triangles extend beyond the intended object boundaries.

Any suggestions on how to improve this process? Is there a way to display a 2D flat object (represented by a vertex array) in 3D space without converting it to triangles?

Answer №1

Exploring a new idea with the use of quaternions:

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

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

scene.add(new THREE.AxesHelper(3));

var rawPoints = [{
  "x": 10,
  "y": 10,
  "z": 1
}, {
  "x": 9.421052631578952,
  "y": 11.736842105263158,
  "z": 6.789473684210525
}, {
  "x": 5,
  "y": 12.142857142857142,
  "z": 7.7142857142857135
}, {
  "x": 5.285714285714286,
  "y": 13,
  "z": 10.628571428571426
}, {
  "x": -1,
  "y": 13,
  "z": 10
}, {
  "x": 0,
  "y": 10,
  "z": 0
}]

var points = [];
rawPoints.forEach(r => {
  points.push(new THREE.Vector3(r.x, r.y, r.z));
});

var tri = new THREE.Triangle(points[2], points[1], points[0]);
var normal = new THREE.Vector3();
tri.getNormal(normal);

var baseNormal = new THREE.Vector3(0, 0, 1);
var quaternion = new THREE.Quaternion().setFromUnitVectors(normal, baseNormal);

var tempPoints = [];
points.forEach(p => {
  tempPoints.push(p.clone().applyQuaternion(quaternion));
})

var shape = new THREE.Shape(tempPoints);
var shapeGeom = new THREE.ShapeGeometry(shape);
var mesh = new THREE.Mesh(shapeGeom, new THREE.MeshBasicMaterial({
  color: "red",
  side: THREE.DoubleSide,
  wireframe: false
}));
console.log(points);
mesh.geometry.vertices = points;
scene.add(mesh);

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

Creating a secured page with Node.js and Express: Password Protection

I am a beginner with node.js/express! Currently, I am working on developing a chat site along with a chat admin site. When I navigate to _____:3000/admin, it prompts me for a password through a form. I am looking for a way to verify if the entered passwor ...

Tips for using jQuery to identify the most recently modified row in an HTML table

Is there a way to identify the most recently modified (either newly added or changed) row in an HTML table? ...

I have successfully managed to populate the Google Apps Script listbox based on the previous listbox selection for two options, but unfortunately, I am encountering issues

Struggling to set up 3 list boxes that populate based on each other? At the moment, I have one list box fetching data from a spreadsheet. Could someone assist me in configuring it so that the second list box populates based on the first, and a third list b ...

I can't seem to figure out why my characters keep disappearing from the HTML string when I attempt to dynamically add HTML using JavaScript

I am currently facing an issue with dynamically adding links to a page. The links are being added successfully, however, the '[' and ']' at the beginning and end of the line are disappearing. Here is the code snippet from my .js file: ...

Automatically generated VueJS function

Creating a logging system for my Javascript Project using VueJS and Vuex To make logging methods accessible to all components, I am utilizing a global Mixin : import { mapState, mapActions } from 'vuex' import LogLevel from '@/enums/logger ...

Using Vue.js to pass a variable from a parent component to a child component

Parent component: ShowComment Child component: EditComment I'm attempting to pass the value stored in this.CommentRecID to the child component. In the template of ShowComment, I have included: <EditComment CommentRecID="this.CommentRecID" v-if= ...

Encountering ENOENT error with Node.js file preview

I am attempting to utilize the filepreview tool to extract an image from a docx document. I have successfully installed it using the command npm install filepreview. This is the code snippet I am working with: const filepreview = require('fileprevie ...

What are the steps for implementing webpack 5 configurations in Next.js?

I can't seem to figure out how to properly add experiments to my webpack config. Here is my current environment: [email protected] [email protected] To set up, I started a new Next.js app using the command npx create-next-app blog Accord ...

Retrieve the value of a nested JSON object using the name of an HTML form field, without the use of eval

I am facing a similar issue to Convert an HTML form field to a JSON object with inner objects, but in the opposite direction. Here is the JSON Object response received from the server: { company : "ACME, INC.", contact : { firstname : "Da ...

Managing checkbox inputs within a MEAN stack application

As someone who is brand new to the MEAN stack, I've been experimenting with saving an array of checkbox values and retrieving them from MongoDB. I've set up a clear schema for embedded arrays using Mongoose, but I'm struggling with how to in ...

Ways to leverage ember.js in a serverless environment

After checking out the example of ember.js on this website (http://todomvc.com/), I decided to clone the project onto my computer. Upon double-clicking the index.html file, the project ran smoothly, just as I had anticipated. However, following the instru ...

Generate visual representations of data sorted by category using AngularJS components

I am facing an unusual issue with Highcharts and Angularjs 1.6 integration. I have implemented components to display graphs based on the chart type. Below is an example of the JSON data structure: "Widgets":[ { "Id":1, "description":"Tes ...

Tips for halting the movement of marquee text once it reaches the center briefly before resuming animation

Is there a way to make text slide in, pause when centered, and then repeat the process? I'm looking for some help with this animation. Here is the code snippet: <marquee direction="left" id="artistslide"> <span id="currentartist">< ...

Looping through a nested for loop within an HTML table

I am currently working on generating a dynamic table using Lists of varying sizes. My first list is a List of Cars List<Car>. I have successfully placed the names of different car companies in the header. Next, I have a List<List<CarSales>& ...

Modify the JS/JQuery variable by utilizing the data entered into an HTML input field

I have implemented a javascript/ajax request on my advanced search page. <script> // window.setInterval(function() // { $(function () { var SearchTerm = '<?php echo $_POST['Search']; ...

ReactJS experiencing issue with the functionality of the all-the-cities library

Encountering an issue where importing the library all-the-cities causes reactjs to malfunction and display the following error: TypeError: fs.readFileSync is not a function (anonymous function) C:myproject/node_modules/all-the-cities/index.js:6 3 | cons ...

Troubleshooting the malfunctioning AngularJS ui-view component

My ui-view isn't functioning properly, but no errors are being displayed. Can anyone help me figure out what I'm missing to make this work? This is the main template, index.html. <!DOCTYPE html> <html> <head> <meta charset= ...

Having difficulty personalizing the email template on AWS SES

I am currently working on setting up a forgot password email system using AWS SES. Below is the template I have created: { "Template":{ "TemplateName": "forgotpasswrd", "SubjectPart": "Forgot ...

Show off a sleek slider within a Bootstrap dropdown menu

Is there a way to display a sleek slider within a Bootstrap dropdown element? The issue arises when the slider fails to function if the dropdown is not open from the start, and the prev/next buttons do not respond correctly. For reference, here is my curr ...

Unusual behavior observed in AngularJs local variables

This code snippet is from the controller: cat1=[]; $.getJSON('categories/1/', function(data) { cat1 = data; //this returns a JSON object }); //cat2..4 are also JSONs $scope.pictures=[cat1,cat2,cat3,cat4,cat5]; The issue here seems to be th ...