What is the best way to tile textures in Three.js without causing distortion?

Despite trying various solutions, I am still facing an issue where my textures appear to be stretched or scaled based on the mesh size. In a bid to seek a resolution, here are some key points to note:

  • All textures have dimensions of 64x64 pixels
  • I have preloaded all textures
  • The Web GL renderer is being used

Below is a snippet of my code:

makeTestObject:function()
{
    var scope = this,
        tileGeometry = new THREE.BoxGeometry(TILE_SIZE , TILE_HEIGHT , TILE_SIZE),
        texture = new THREE.Texture(preloadedImageObject),
        textureMaterial = new THREE.MeshLambertMaterial({map:texture}),
        tile = new THREE.Mesh(tileGeometry , new THREE.MeshFaceMaterial(
        [
            textureMaterial, // +x
            textureMaterial, // -x
            textureMaterial, // +y
            textureMaterial, // -y
            textureMaterial, // +z
            textureMaterial // -z
        ]));

    texture.wrapS = THREE.RepeatWrapping;
    texture.wrapT = THREE.RepeatWrapping;

    tile.position.y = BASE_HEIGHT * 2;
    tile.castShadow = true;
    tile.receiveShadow = true;
    texture.needsUpdate = true;
    scope.scene.add(tile);
}

However, when I use texture.repeat.set(x , x) with any value for x, the texture seems to vanish and only a flat color is left behind.

Could someone shed light on what might be going wrong in my implementation?

Answer №1

Alright, when dealing with a standard box shape (whether square or rectangular), the solution can be summarized as follows:

generateBoxObject:function()
{
    var context = this,
        boxGeometry = new THREE.BoxGeometry(BOX_SIZE , BOX_HEIGHT , BOX_SIZE),
        texture = new THREE.Texture(preloadedImageAsset),
        material = new THREE.MeshLambertMaterial({map:texture}),
        box = new THREE.Mesh(boxGeometry , new THREE.MeshFaceMaterial(
        [
            material, // +x
            material, // -x
            material, // +y
            material, // -y
            material, // +z
            material // -z
        ]));

    texture.wrapS = THREE.RepeatWrapping;
    texture.wrapT = THREE.RepeatWrapping;
    box.geometry.computeBoundingBox();

    var maxBound = box.geometry.boundingBox.max;
    var minBound = box.geometry.boundingBox.min;
    var surfaceHeight = maxBound.y - minBound.y;
    var surfaceWidth = maxBound.x - minBound.x;

    texture.repeat.set(surfaceWidth / TEXTURE_DIMENSIONS , surfaceHeight / TEXTURE_DIMENSIONS);

    texture.needsUpdate = true;
    context.scene.add(box);
}

The crucial aspect lies in accurately configuring the ratios for repeating the texture. Additionally, it is advisable to create distinct materials for each face instead of reusing the same material object repetitively.

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

Insert text within the switch component using Material-UI

Looking to customize Material UI's Switch component with text inside? Check out the image below for an idea of what I'm going for. https://i.stack.imgur.com/KadRZ.png Take a look at my code snippet: import React from 'react'; import S ...

What is the reason for the num pad being classified as a character?

Everything is functioning correctly, but when I use the number pad on the right side of my keyboard, it registers as a character and gets deleted. However, the numbers on the left side are accepted without any issue. I want to be able to input numbers usin ...

Problem concerning the window object in a React functional component

Hey there, I am currently facing a situation where I need to access the window object within my React component in order to retrieve some information from the query string. Here is an excerpt of what my component code looks like: export function MyCompone ...

The requested external js scripts could not be found and resulted in a net::ERR_ABORTED 404 error

import express, { Express, Request, Response } from 'express'; const path = require("path"); import dotenv from 'dotenv'; dotenv.config(); const PORT = process.env.PORT || 5000; const app = express(); app.use(express.static(path.join ...

Leveraging web workers for asynchronous API calls

Trying to find an efficient method for utilizing web workers to handle api calls, my current approach involves the following on the client side: - worker-client.js export const workerFetch = (method = "get", url = "/", data = {}) => new Promise((res ...

What causes identical request headers to result in receiving different Ajax content?

Whenever I access the website for a journal called Applied Physics Letters at "", I notice that there are multiple AJAX fields on the page. Each time I click "show abstract", the abstract for the corresponding article is displayed. By using "inspect elemen ...

Difficulty with obtaining .responsetext in AJAX and PHP

On my real estate website, I have a form for users to 'Add a Property'. Although I will implement form validation later on, here is the current html/js code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR ...

Validate if a string in JQuery contains a specific substring

How can I determine if one string contains another string? var str1 = "ABCDEFGHIJKLMNOP"; var str2 = "DEFG"; What function should I utilize to check if the string str1 includes the string str2? ...

Angular directive becomes disabled when transferred between different DOM elements

In my app, I utilize a modal service that handles the opening and closing of modals. The modal retrieves its content from a specific div with an ID located within a hidden container element. This process typically functions correctly. The issue I am encou ...

Having trouble with Grunt and Autoprefixer integration not functioning properly

Joining a non-profit open source project, I wanted to contribute by helping out, but I'm struggling with Grunt configuration. Despite my research, I can't seem to figure out why it's not working. I am trying to integrate a plugin that allow ...

Is there a way to identify which elements are currently within the visible viewport?

I have come across solutions on how to determine if a specific element is within the viewport, but I am interested in knowing which elements are currently visible in the viewport among all elements. One approach would be to iterate through all DOM elements ...

What is the easiest way to include a copyright symbol in a React component?

I am trying to include the copyright symbol in a React component, but it doesn't seem to be working for me. function Footer() { return ( <footer> <p>&copy</p> </footer> ); } <p>&copy</p> ...

Prevent left click on HTML canvas and enable right click to pass through with pointer-events

In my scenario, I have an HTML canvas positioned above various other HTML elements that detect right-click mouse events. The goal is to be able to draw on the canvas with the left mouse button while simultaneously interacting with the underlying HTML eleme ...

Access the Ajax response and store it in a JavaScript variable

I've successfully created a script that inserts data into an MySQL database using a modal and AJAX. However, I'm having trouble retrieving the response to complete an input field. Below is my current script: $.ajax({ url:"insertar_cl ...

The toggle feature in Bootstrap is stuck in the "on" position and refuses to "untoggle."

Currently, I am working on developing a basic website using Laravel and Vue.js. To ensure that the website is responsive, I integrated Bootstrap 4 into the project. For the most part, everything appears to be functioning correctly - the navbar collapses as ...

Attempting to utilize the async/await method to retrieve a service, but unfortunately, the returned values from the second service are not populating my variables as intended

I am having an issue with my service where I retrieve a list from the server. The problem is that within this list, I need to make another service call to fetch logo images. Although the service call returns successfully, my list still remains empty. Can y ...

Unable to access a hyperlink, the URL simply disregards any parameters

When I click an a tag in React, it doesn't take me to the specified href. Instead, it removes all parameters in the URL after the "?". For example, if I'm on http://localhost:6006/iframe.html?selectedKind=Survey&selectedStory=...etc, clicking ...

Using $regex in mongodb's pipeline operations allows for advanced string

I need to be able to use $regex in order to search for any words that contain a specific keyword provided by the user, but I'm experiencing issues. Here's what I have so far: aggregatePipeline.push({ $match: { name: { $reg ...

Decoding a formatted string

Here is a string that needs parsing: const str = 'map("a")to("b");map("foo")to("bar");map("alpha")to("beta");' The goal is to generate a JSON structure like this: [{id: 'a', map: 'b'}, {id: 'foo', map: 'bar&a ...

Basic selection menu layout

I have put together a basic menu for my WordPress site without relying on classes or IDs: <div class="main-menu"> <nav> <ul> <li> <a href="#" class="menu-link">home</a> ...