Learn the steps to effortlessly create a basic square by utilizing BufferGeometry

Is it possible to create a simple square shape using BufferGeometry? Rather than drawing 120000 triangles, I just want to reduce it to two triangles that form a square.

<html>
<head>
    <title>test app</title>
    <style>canvas { width: 100%; height: 100% }</style>
</head>
<body>
    <script src="three.min.js"></script>
    <script>
        var scene = new THREE.Scene();
        var camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);

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

        var triangles = 2;

        var geometry = new THREE.BufferGeometry();
        geometry.attributes = {
            index: {
                itemSize: 1,
                array: new Uint16Array(triangles * 3),
                numItems: triangles * 3
            },
            position: {
                itemSize: 3,
                array: new Float32Array(triangles * 3 * 3),
                numItems: triangles * 3 * 3
            },
            normal: {
                itemSize: 3,
                array: new Float32Array(triangles * 3 * 3),
                numItems: triangles * 3 * 3
            },
            color: {
                itemSize: 3,
                array: new Float32Array(triangles * 3 * 3),
                numItems: triangles * 3 * 3
            }
        }

        var color = new THREE.Color();

        var indices = geometry.attributes.index.array;
        var positions = geometry.attributes.position.array;
        var normals = geometry.attributes.normal.array;
        var colors = geometry.attributes.color.array;

        for (var i = 0; i < indices.length; i++) {
            indices[i] = i % (3 * 1);
        }

        for (var i = 0; i < positions.length; i += 9) {
            positions[i] = 0;
            positions[i + 1] = 0;
            positions[i + 2] = 0;

            positions[i + 3] = 0;
            positions[i + 4] = 1;
            positions[i + 5] = 0;

            positions[i + 6] = 1;
            positions[i + 7] = 0;
            positions[i + 8] = 0;

            color.setRGB(55, 202, 55);

            colors[i] = color.r;
            colors[i + 1] = color.g;
            colors[i + 2] = color.b;

            colors[i + 3] = color.r;
            colors[i + 4] = color.g;
            colors[i + 5] = color.b;

            colors[i + 6] = color.r;
            colors[i + 7] = color.g;
            colors[i + 8] = color.b;
        }

        var material = new THREE.MeshBasicMaterial({color: 0x00ff00});
        var square = new THREE.Mesh(geometry, material);
        scene.add(square);

        camera.position.z = -5;

        var render = function () {
            requestAnimationFrame(render);

            square.rotation.x += 0.1;
            square.rotation.y += 0.1;

            renderer.render(scene, camera);
        };

        render();
    </script>
</body>

Answer №1

The latest version of three js does not allow you to assign index as demonstrated by @calvin-sydney. Instead, the setIndex method from THREE.BufferGeometry must be used.

geometry.addAttribute('uv', new THREE.BufferAttribute(new Float32Array(uvs), 2));
geometry.addAttribute('position', new THREE.BufferAttribute(new Float32Array(positions), 3));
geometry.addAttribute('normal', new THREE.BufferAttribute(new Float32Array(normals), 3));
geometry.addAttribute('color', new THREE.BufferAttribute(new Float32Array(colors), 3));

geometry.setIndex( new THREE.BufferAttribute( new Uint32Array( indices ), 1 ) );

Answer №2

If you're experiencing issues with your camera settings, here is a solution to help resolve them: When setting up your camera for near and far view, make sure the values fall within the range of 0.1 to 1000.

var camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);

It's important to adjust your vertices' z position to fit within this range as well. To do so, modify your code from

positions[ i + 2 ] = 0; 

to

positions[ i + 2 ] = 1;

Additionally, ensure that these essential parts are not missing in your code:

geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 3 ) );
geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );

For a complete version of the corrected code, refer to the following link:

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

Using JQuery to emphasize selected radio button area

Can someone help me modify the code to highlight the checked radio button by adding or removing a class from the <span class " ui-message ui-state-highlight"> element? Below is the HTML and JS code: $(document).ready(function(){ $('# ...

Tips for leveraging Angular resources with Sails

I recently started using angular resource with sails. var roles = sailsResource('roles').query(); // GET /roles $scope.rolesList = roles; angular.forEach($scope.rolesList, function(role) { console.log("Role: " + role); }); The output is sh ...

The Google Books API initially displays only 10 results. To ensure that all results are shown, we can implement iteration to increment the startIndex until all results have

function bookSearch() { var search = document.getElementById('search').value document.getElementById('results').innerHTML = "" console.log(search) var startIndex = I have a requirement to continuously make Ajax calls ...

What is the best way to handle both local and global ajax events in jQuery?

After recently transitioning from Prototype to jQuery, I am encountering some challenges. My application involves multiple AJAX requests, where I want certain global events to take place in 95% of cases, such as displaying or hiding a loading indicator. A ...

Can the mapnik node module be used with newer versions of Node (such as 4.0.0)?

I'm currently running node version 0.12.0, but I'm considering upgrading to node version 4.0.0. However, I have concerns about whether mapnik is compatible with the newer version of Node. The documentation only mentions support for Node v0.10.x o ...

Select: Exchange icon when clicked

UPDATE MENU ICON jsfiddle.net/a3MKG/83/ Can someone provide guidance on how to change the menu icon image upon clicking it? I would like the icon to switch to a different image (such as an X) once it has been clicked. Please Note: When the menu icon is c ...

Enable autocomplete feature in a PHP form once the user starts typing their name

After searching for similar questions, I couldn't find any with the same "variables," so here's my dilemma: I have a basic form where I input a name and I want the rest of the form to be filled in automatically (ID). Retrieving data from the da ...

Node seems to be having trouble with exporting and requiring, as it claims the class is not defined

Within my codebase, I have created three essential classes: TypeChecker: require('./type_error_checker/TypeErrorChecker'); require('./transpiler/Transpiler'); class TypeChecker { constructor() { console.log("TypeChecker i ...

Using Three JS to recycle the geometry of a previously imported object

Is there a way to efficiently re-use imported object geometries in Three JS without duplicating them in memory? I've tried writing a loader but it doesn't seem to update the geometry once loaded. var tmpGeo = geometries[ID]; if (!tmpGeo) { t ...

Oops! The system encountered a problem: the property 'modalStack' is not recognized on the type 'NgxSmartModalService'. Maybe you meant to use '_modalStack' instead?

Currently, I'm facing an issue while attempting to run ng build --prod in my Angular 6 project. I have also incorporated the NgxSmartModal package for handling modals. Unfortunately, the build process is failing and I can't seem to figure out why ...

The issue of race condition in Node.js programming

I've been diving into the documentation, but I'm struggling to figure out what's going on here. I have two functions: one downloads a CSV file via a URL, and the next function takes that CSV file and converts it to JSON FileDownload.js co ...

unable to attach picture to the img element

Currently, I am honing my skills in Windows Phone development through WinJS. In my latest project, I have crafted a code snippet that parses JSON data fetched from a specific URL. The objective is to bind the images retrieved to a list view on an HTML page ...

Assign a value to a dropdownlist in Javascript

I am facing an issue with setting the selected value of a dropdownlist that is populated by a webservice using ajax cascading dropdown. It seems like the values are not available when the javascript code runs, even though I have placed it at the bottom o ...

Rotating images on a canvas

We're currently implementing Ionic and Angular in our project. One issue we are facing is regarding image rotation on canvas. When we click on an image, the rotation works perfectly if it's a jpg file. However, when we pass a base64 image, the r ...

Obtain the Encoded Data

Unfortunately, I do not have control over domain.com. However, I am able to provide a redirect URL parameter like the one shown below: www.domain.com?retUrl=www.example.com%3Fparameter%3Dvalue Following the provision of retURL (www.example.com?parameter= ...

Executing a callback function in AngularJS after dynamically rendering elements with `ng-repeat`

Many posts demonstrate how to implement callback functions in directives to wait for ng-repeat to finish before calling a function. Here is an example: <div ng-repeat="Object in Objects" class="objectClass" on-finish-render>{{Object.Overlay}</div ...

Issue with JavaScript HTML Section Changer not functioning properly

I need to implement a button that switches between two pages when pressed. Although the code seems simple, I am struggling to make it work. HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"& ...

Is it possible for the HTML data attribute to store a direct link to a specific DOM element?

Can the HTML data- attributes be used to store a reference to another DOM element? As shown in this jQuery example: var domel1 = document.getElementById("#mydiv"); var domel2 = document.getElementById("#mydiv2"); $(domEl1).attr('data-domel', dom ...

Display a PDF file within an IFrame using JavaScript and then print it

Why is it so challenging to achieve? I've dedicated 48 hours to research this, yet it seems impossible! Although recent Chrome versions allow the parent window to access PDFs in iframes, both FF and IE prevent any interaction with the iframe that dis ...

Verify that the length of all input fields is exactly 7 characters

My task involves checking the length of multiple input fields that share a common class. The goal is to verify that all fields have a length of 7. After attempting a solution, I encountered an issue where even if the length of all fields is indeed 7, the ...