Issue with Image Display on Plane Using ThreeJS

I am struggling to apply a square grass texture to square planes in ThreeJS. Each plane should display the grass texture once, but instead, each plane is rendering as a different solid color. It seems like ThreeJS is applying the texture one pixel at a time to each plane, rather than rendering the entire texture on each plane.

Below is my code snippet:

<!DOCTYPE html>
<html>
  <head>
    <title>Neighbor</title>
    <style>
      html, body { margin: 0; padding: 0; overflow: hidden; }
    </style>
  </head>
  <body>
    <script src="third_party/three.min.js"></script>
    <script>
      var scene = new THREE.Scene();

var aspect = window.innerWidth / window.innerHeight;


var camera = new THREE.PerspectiveCamera( 95, aspect, 0.1, 1000 );
//var camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, 1, 1000 );        

camera.position.y = 20;
camera.position.z = 20;

var renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );      

var geometry = new THREE.PlaneGeometry( 1, 1 );


// instantiate a loader
var loader = new THREE.TextureLoader();
loader.crossOrigin = true;
var material;
// load a resource
loader.load(
    // resource URL
    'grass2.png',
    // Function when resource is loaded
    function ( texture ) {
        // do something with the texture
        material = new THREE.MeshBasicMaterial( {
            map: texture
         } );
    },
    // Function called when download progresses
    function ( xhr ) {
        console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
    },
    // Function called when download errors
    function ( xhr ) {
        console.log( 'An error happened' );
    }
);

//var material = new THREE.MeshBasicMaterial( {color: 0x81D67E} );
var plane = [];
for(var j=0;j<100;j++){
for(var i=0;i<100;i++){
    plane[i] = new THREE.Mesh( geometry, material );
    plane[i].rotation.x = -(Math.PI / 2);
    plane[i].position.z = -(i * 1);
    plane[i].position.x = (j * 1);
    scene.add( plane[i] );
}
}
for(j=1;j<100;j++){
for(i=0;i<100;i++){
    plane[i] = new THREE.Mesh( geometry, material );
    plane[i].rotation.x = -(Math.PI / 2);
    plane[i].position.z = -(i * 1);
    plane[i].position.x = -(j * 1);
    scene.add( plane[i] );
}
}


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

    renderer.render( scene, camera );
};

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

The current output can be seen here:

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

And this is the texture I'm trying to load:

https://i.sstatic.net/72W3n.png

Update: The colors of the planes change every time the page is reloaded.

Answer №1

It is recommended to create the material outside of the loaded callback function for better efficiency.
For example:

// Initialize a loader
var loader = new THREE.TextureLoader();
loader.crossOrigin = true;
var material = new THREE.MeshBasicMaterial();
// Load a resource
loader.load(
    // Resource URL
    'grass2.png',
    // Function when resource is loaded
    function ( texture ) {
        // Implement texture functionality
        material.map = texture;
        material.needsUpdate = true;
    },
    // Function called during download progress
    function ( xhr ) {
        console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
    },
    // Function called when download errors occur
    function ( xhr ) {
        console.log( 'An error occurred' );
    }
);

Consider using one large plane with repeated textures rather than multiple smaller planes.
For example:

texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set( 100, 100 );

Do you have a specific reason for using small dimensions on your plane geometry?

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

Transforming a bezier curve into a flat surface in three.js

I am currently working on creating a curved road in three.js using bezier calculations. However, I am facing a challenge in converting the sequence of curved lines into a curved plane. Within my 3D scene, I have cars, a road made from a plane, and a path ...

Solutions for Showing Pop-up Tabs in React Native Webview

I have a website that displays content based on user subscription status. If the subscription is active, a book is loaded; otherwise, if it's expired, a specific page is shown: https://i.sstatic.net/HLv0B.png To enhance user experience, I preload th ...

Issues with the execution of Jquery function

Hey guys, take a look at my code: //Additional Jquery codes // display_popup_crop : revealing the crop popup function display_popup_crop(link) { alert("show_popup_crop function is triggered!"); // changing the photo source $('#cropbox&a ...

Challenges faced when dealing with MongoDB and the latest version of webpack

Struggling to navigate MongoDB and React.js, encountering issues with MongoDB dependencies. Here are the dependencies listed in package.json: "dependencies": { "dotenv": "^16.3.1", "mongodb": "^4.1.0", &qu ...

Leveraging Node.js to efficiently handle large Excel files within a SAP S/4HANA application

I am seeking assistance with a challenge I am currently facing (please note that I am not a JavaScript developer). Any help would be greatly appreciated. Procedure: The user uploads an Excel file from the UI. In the backend, we utilize xlsx/exceljs Java ...

Troubleshoot: How to Fix the socket.io net::ERR_CONNECTION_TIMED_OUT

I am facing an issue with my website's real-time chat functionality. It works perfectly on localhost without any errors. However, when I try to run it on the server, I encounter the following error: http://my.domain:52398/socket.io/?EIO=3&transpo ...

Why does a basic multiline regex work in ECMAScript but not in .NET?

Currently, I am working on a small utility program in C# that aims to enhance all of my Visual Studio C# item templates by adding extra using ; statements. To achieve this, I have developed a simple regular expression to extract the existing namespace impo ...

What is the process for attaching an iterator to the name value of every element within a cloneNode?

Consider the following scenario: <div id="addNewMenuElementPart2"> Numerous elements with a name attribute are present here. </div> <div id="addNewMenuElementPart3Optional"></div> Additionally, t ...

npm-bundle encounters an issue with Error: ENOENT when it cannot find the file or directory specified as 'package.json'

npm-bundle is throwing an error that says Error: ENOENT: no such file or directory, open 'package.json' in my NodeJs project. It works fine if I manually create test.js and package.json, then run npm install followed by npm-bundle. However, when ...

Discover the ways in which an AngularJS function is able to generate HTML code containing an AngularJS

There is an issue here helper.getDataForTriggeredUploadOfMFFile = function (isTriggeredUploadMF) { if (!isTriggeredUploadMF) { return 'None'; } else { return '<spa ng-click=\"previewDataOnSmartAnalytics()>Preview Data</span&g ...

Creating a JSON object in AngularJS is a simple and straightforward process

Is it a good practice to create a JSON object in AngularJS this way? Or is there a better solution to achieve the desired format? Edit question: I am trying to create an object in JSON format as shown below. I have written the code but facing difficulty ...

Adjust the background color using jQuery to its original hue

While working on a webpage, I am implementing a menu that changes its background color upon being clicked using jQuery. Currently, my focus is on refining the functionality of the menu itself. However, I've encountered an issue - once I click on a men ...

Loop through the array only if the property exists to avoid encountering the 'cannot iterate over undefined' error

Here's a code snippet that I'd like to simplify: if (this.props.fk_data) { if (this.props.fk_data.length > 0) { for (let fk_dataset of this.props.fk_data) { } } } I'm considering putting this.props.fk_data into st ...

Google AdSense is unable to detect code fragments within the header of a Next.js website

Hello, I've been trying to set up Google AdSense on my Next.js site, but AdSense doesn't seem to recognize it. I keep receiving an error saying that I need to place the code inside my headers. How can I properly implement this? Below is my _docum ...

Getting URL Parameters in Angular JS

How should one go about retrieving URL parameters in Angular? For instance, consider this URL: http://example.com/mypage.html?product=1234®ion=4&lang=en Thank you ...

I'm having issues with my flipclock moving too quickly and skipping over certain numbers. Any suggestions on how to resolve this issue?

My flip clock script is behaving oddly, moving too quickly and skipping over even numbers. I've been playing around with the code, and it seems like there's a problem when I use the callbacks function. var clock = $('#clock3').FlipClo ...

Jest fails to pass when encountering the double colon

Having issues testing a React app using Jest. I encounter errors when running my code: FAIL src\App.test.js ● Test suite failed to run C:/Users/user1/Projects/map-editor/src/App.js: Unexpected token (40:33) 38 | <div cla ...

Querying MongoDB with Mongoose to find objects in an array based on a specific date stored

I am currently working on constructing a mongoose query to retrieve records that match a specific date. It seems like the query is functioning properly, but I'm not getting any results displayed because the date stored in my array of objects is a stri ...

Exploring the capabilities of NEXTJS for retrieving data from the server

When trying to retrieve data from the nextjs server on the front end, there is an issue with the code following the fetch() function inside the onSubmit() function. Check out the /test page for more details. pages/test const onSubmit = (data) => { ...

Using <br> within an angular expression

I am facing an issue with the following expression: <td>{{student.name}}<br>{{student.age}}<br>{{student.fathername}}</td> When displayed, it looks like this: shane<br>26<br>greg Is there a way to break this into a ...