Creating a 3D polygon in three.js using three vertices

I've been attempting to render a plane using a set of 3 vertices (shown below). Unfortunately, none of the methods I have tried - mostly sourced from SO or the official three.js forum - seem to be working for me.

// example vertices
const vert1 = new THREE.Vector3(768, -512, 40)
const vert2 = new THREE.Vector3(768, -496, 40)
const vert3 = new THREE.Vector3(616, -496, 40)

I have already experimented with code in order to calculate the width and height of the plane. However, I find my current approach to be overly complex since it only accounts for X and Y coordinates. I fear that if I were to incorporate Z-coordinates and the position of the plane into this logic, the code would become exponentially more convoluted.

const width = vert1.x !== vert2.x ? Math.abs(vert1.x - vert2.x) : Math.abs(vert1.x - vert3.x)
const height = vert1.y !== vert2.y ? Math.abs(vert1.y - vert2.y) : Math.abs(vert1.y - vert3.y)

For instance, I aim to generate a plane defined by points A, B, and C as well as another one defined by points D, E, and F.

Check out this Example Video

Answer №1

If you need to create a plane based on three coplanar points, you can utilize the THREE.Plane.setFromCoplanarPoints() method. Keep in mind that a THREE.Plane object represents an infinite plane dividing the 3D space into two halves mathematically. To visually represent it, consider using a THREE.PlaneHelper. Alternatively, you can refer to this thread for a method to generate a plane mesh from your THREE.Plane instance:

Three.js - PlaneGeometry from Math.Plane

Answer №2

An algorithm has been developed to compute the midpoint of the longest edge of a triangle. By calculating a vector from a point that is not on the longest edge to this midpoint and adding it back to the midpoint, the coordinates of the fourth point can be obtained.

To conclude, a PlaneGeometry is created from these points and a mesh is generated using TypeScript.

type Line = {
    startPoint: Vector3;
    startPointIdx: number;
    endPoint: Vector3;<br>
    endPointIdx: number;
    vector: Vector3;
    length: Vector3;
}

function createTestPlaneWithTexture(): void {
    const pointsIn = [new Vector3(28, 3, 3), new Vector3(20, 15, 20), new Vector3(1, 13, 3)];
    const lines = Array<Line>();

    for (let i = 0; i < pointsIn.length; i++) {
        let length, distVect;
        if (i <= pointsIn.length - 2) {
            distVect = new Vector3().subVectors(pointsIn[i], pointsIn[i + 1]);
            length = distVect.length();
            lines.push({ vector: distVect, startPoint: pointsIn[i], startPointIdx: i, endPoint: pointsIn[i + 1], endPointIdx: i + 1, length: length });
        } else {
            const distVect = new Vector3().subVectors(pointsIn[i], pointsIn[0]);
            length = distVect.length();
            lines.push({ vector: distVect, startPoint: pointsIn[i], startPointIdx: i, endPoint: pointsIn[0], endPointIdx: 0, length: length });
        }
    }

    let maxLine: LineType;
    lines.forEach(line => {
        if (maxLine) {
            if (line.length > maxLine.length)
                maxLine = line;
        } else {
            maxLine = line;
        }
    });

    const midPoint = maxLine.endPoint.clone().add(maxLine.vector.clone().multiplyScalar(0.5));
    const idx = [0, 1, 2].filter(value => value !== maxLine.endPointIdx && value !== maxLine.startPointIdx)[0];
    const thirdPoint = pointsIn[idx];
    const vec = new Vector3().subVectors(midPoint, thirdPoint);
    const fourthPoint = midPoint.clone().add(vec);
    const edge1 = thirdPoint.clone().sub(maxLine.endPoint).length();
    const edge2 = fourthPoint.clone().sub(maxLine.endPoint).length();

    const points = [thirdPoint, maxLine.startPoint, maxLine.endPoint, fourthPoint];

    const geo = new PlaneGeometry().setFromPoints(points);

    const texture = new TextureLoader().load(textureImage);
    texture.wrapS = RepeatWrapping;
    texture.wrapT = RepeatWrapping;
    texture.repeat.set(edge2, edge1);
    const mat = new MeshBasicMaterial({ color: 0xFFFFFFF, side: DoubleSide, map: texture });
    const plane = new Mesh(geo, mat);
}

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

What is the best way to update comments after submitting an AJAX request?

I stumbled upon a lightweight script that allows for submitting WordPress comments via AJAX. Although the comments are successfully submitted, the new comment does not appear immediately; only the comment count gets updated. Upon manually refreshing the pa ...

JavaScript issue: Shallow copy does not reflect updates in nested JSON object

Within my coding project, I came across a nested JSON object that looks like this: var jsonObj = { "level1" : { "status" : true, "level2" : {} // with the potential to extend further to level 3, 4, and beyond } } My objective is si ...

When using an OrthographicCamera in Three.js, the canvas particles may not be rendered properly

After replacing the perspective camera with an orthographic one in the Three.js canvas_lines demo, I noticed that the particles stopped rendering while the lines still appeared. This observation has raised a question in my mind: is this issue caused by a b ...

Tips on utilizing setInterval in a Vue component

When defining the timer in each individual my-progress, I use it to update the value of view. However, the console shows that the value of the constant changes while the value of the view remains unchanged. How can I modify the timer to successfully change ...

Navigating between divs with a 100% height using up and down movements

I am working on a website that is structured into different sections using divs with shared classes but unique IDs. Each div is set to take up 100% of the viewport height. To navigate between these sections, I want to provide Up/Down arrow buttons for user ...

Executing a JavaScript function in ASP.NET after a button click has been completed

Here is an ASP.NET button: <asp:Button ID="okButton" runat="server" Text="Okay" OnClick="okButton_Click" /> This is the okButton_Click function: protected void okButton_Click(object sender, EventArgs e){ //perform tasks here } There is also a Ja ...

Developing a nested JSON structure

I'm struggling with a seemingly simple task of creating a JSON object. Despite my efforts, I can't seem to find the right information to guide me through it. Here is what I have so far: var myJsonObject = new Object(); myJsonObject.context.appli ...

jQuery's :last selector allows you to target the last

I need assistance with my jQuery code $('#share_module:last').css("background-color","red"); Unfortunately, it is only affecting the first #share_module Here is an example of the HTML structure: <div id = "share_module" class = "id of the ...

utilize ng-bind to apply numerous values simultaneously

Is it possible to bind multiple values using ng-bind in the following manner : <p ng-bind="instructor.first_name instructor.last_name"></p> Every time I attempt this, I encounter the following error: Error: $parse:syntax Syntax Error I am a ...

Using dot notation for event handlers in Vue.Js is a handy technique

I am currently developing a Single Page Application (SPA) using Vue.js 3 and Bootstrap 5. On the main page, I have implemented the Bootstrap Offcanvas element with code that closely resembles the one provided in the documentation. The structure of the off ...

Transferring data from JavaScript to PHP through Ajax communication

Allowing users to comment on your page and saving those comments in a database is an important feature. While you have the database part covered, you are looking for assistance with passing text input from JavaScript to PHP. Your goal is to echo the ' ...

Fadein and FadeOut Div transitions are operating correctly in a loop, however, the initial DIV is not being displayed

Why is the first DIV not fading in at all when I have 3 divs set to fade in and out? I'm confident that my code is correct, any ideas? My jQuery/Javascript code: <script type="text/javascript"> $(document).ready(function() { function fade( ...

There was an issue retrieving the value from the $.ajax() error function, as it returned [

After successfully receiving data from the input field and sending it to the database, everything seems to be working fine. However, when attempting to retrieve the data after sending it to the database, an error is encountered: [object HTMLInputElement]. ...

Condense the expression of the Express.js 'app' into a single line

Every time I utilize Express, I find myself consistently needing to do the following: const express = require('express'); const app = express(); Alternatively, to achieve a more coordinated approach, I occasionally opt for this method: const e ...

Why isn't my Enum functioning properly to display the colored background?

Why isn't the Background Color showing up when I pass in the BGColor Prop dynamically in my next.js + Tailwind app? I have tried passing in the prop for my component, but the color is not appearing. <Title title='This is HOME' descripti ...

javascript / php - modify input fields according to selection change

Can anyone help me with an issue I'm facing? I want to update multiple textfields whenever a new option is selected from my dropdown menu. I've written the following code, but it's not working as expected. Can someone figure out what's ...

The output returned by the `reduce()` method cannot be displayed in HTML within a React component when using the `map()` function

Here is the output I am getting: https://i.sstatic.net/E4fK7.png It was generated by the code snippet below: var allblogs = [{ "banner": "41173047269_1594284317134_88820381534.png", "approved_status": 1, "posted_month": "July", "posted_ ...

What is the best way to prioritize loading JSON models first in three.js and declare a variable before initializing?

I am looking to efficiently load multiple JSON models and store them in global variables for easy access. This will streamline tasks like copying, translating, and more without the need to reload a model each time. After trying various methods, I have not ...

Error Encountered: AngularJS - 'DashboardController' is Not Registered

I just set up a new angular app and I'm encountering an issue where my controller is not registering. The error message I am receiving states: The controller with the name 'DashboardController' is not registered. My app module and dashbo ...

Sleek camera motion in three.js

I want to enhance the panorama equirectangular player by adding smooth camera movements. Is it possible to achieve a similar effect as in the cube example while maintaining the smooth transition without disrupting the movement when the mouse is clicked? ...