Ensuring texture consistency for scene backgrounds in three.js

I am facing an issue with adding a background to a scene using a PNG image of 2k resolution. The background appears correctly sized on PC, but on mobile devices, it looks disproportionated. Here is the code snippet I am using:

var texture = THREE.ImageUtils.loadTexture('img/texture.png');

To set the texture as the background of the scene, I simply do this:

scene = new THREE.Scene();
scene.background = texture;

I have come across suggestions to create a separate scene for the background, but I am looking for a simpler solution. Is there a better way to address this issue?

(Please excuse any errors in my English)

Answer №1

If you want to tackle this problem, consider utilizing the THREE.ShaderMaterial

class MyBackgroundPlane extends THREE.Mesh{
    constructor(){
        super( 
            new THREE.PlaneBufferGeometry(2,2,1,1), 
            new THREE.ShaderMaterial({
                uniforms:{
                    uTexture: { value: null },
                    uAspect: { value: 1 }
                },
                vertexShader: `
                    varying vec2 vUv;
                    uniform float uAspect;

                    void main(){

                        vUv = uv; //pass coordinates to screen
                        vUv.x *= uAspect; //scale the coordinates

                        gl_Position = vec4(position.xy, 1., 1.);

                    }

                `,

                fragmentShader:`
                    varying vec2 vUv;
                    uniform sampler2D uTexture;

                    void main(){

                        gl_FragColor = texture2D( uTexture, vUv );
                    }

                `

            })
        )

        this.frustumCulled = false
    }

    setAspect( aspect ){
        this.material.uniforms.uAspect.value = aspect
    }

    setTexture( texture ){
        this.material.uniforms.uTexture.value = texture
    }
}

You'll need to determine the adjustments required for portrait and landscape orientations.

Consider using uniform vec2 uScale; to customize the vertical and horizontal aspects based on the orientation.

Another option is connecting a plane to a camera in the scene graph and managing its scale accordingly.

Answer №2

Consider using a CSS-based background as an alternative method:

#background {
    background-image: url('http://youring.com/test/img/texture.png');
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    z-index: -1;
}

To allow transparency through the canvas, create your renderer like this:

renderer = new THREE.WebGLRenderer( { antialias: true, alpha: true } );

Check out the DEMO here: https://jsfiddle.net/f2Lommf5/5052/

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

Difficulty encountered when displaying JavaScript variable content within HTML in a React component

I'm currently exploring a backend administrative dashboard framework known as admin bro. My current project involves creating a tooltip component, and here is the code I have developed so far. class Textbox extends React.PureComponent { render() { ...

Inquiry regarding the grid structure within my react application

When attempting to arrange my images in a grid layout, I encountered a strange issue after applying CSS grid. The grids ended up being organized horizontally instead of how I wanted them to be - two or three images per line. The component hierarchy is as ...

What is the best way to retrieve information from a database using JSON with PHP, JQUERY, and

Trying to retrieve data from a MySQL database and pass it to a JavaScript file has been quite a challenge. Despite searching extensively online, the examples I found didn't work in my specific scenario. .html file <!DOCTYPE html PUBLIC '-//W ...

determining the perfect size of a container by analyzing its content

Displayed here is a snapshot of content included in form validation for a website project that's currently in development: The content is currently situated within a div element with its width set to 20%. Initially, without this rule, the div spanned ...

Issues arise when using res.send() with ExpressJS and Mongoose

Initially, I have multiple callbacks that need to be executed before sending a res.send() to construct a JSON API: app.get('/api', function (req, res){ ... function logPagesId() { console.log("load: " +pagesId); c ...

Creating a PDF document using HTML code

I am interested in creating a PDF file from an HTML code that includes the stylesheet rules using PHP. Currently, I am attempting to achieve this with the MPDF library. However, the generated PDF does not resemble the original HTML page. Many elements app ...

Error (CODE5022) JavaScript detected in Internet Explorer 10

Here is the code that I wrote: AjxException.reportScriptError = function(ex) { if (AjxException.reportScriptErrors && AjxException.scriptErrorHandler && !(ex instanceof AjxException)) { AjxException.scriptErrorHandler(ex); ...

Error: The function setEmail is not defined. (In 'setEmail(input)', 'setEmail' is not recognized) (Cannot utilize hooks with context API)

App.js const[getScreen, showScreen] = useState(false); const[getEmail, setEmail] = useState(""); <LoginScreen/> <LoginContexts.Provider value={{getEmail,setEmail,getScreen,showScreen}}> {showScreen?<Screen2/>:<LoginScre ...

When hovering over slick text, it becomes hidden because of non-responsive CSS. Are there any solutions to make it responsive?

I can't seem to get the on-hover dates to appear, even though they are rendered when inspecting the page. I suspect it could be related to a responsive CSS issue or class breaking. How can I resolve this? https://i.stack.imgur.com/jyEJb.png https:// ...

Triggering the Bootstrap modal multiple times with each increment

I am experiencing an issue with Bootstrap Modal where the action fires up multiple times upon clicking. <div id="loginModal" class="modal fade"> <div class="modal-dialog"> <div class="modal-content"> ... & ...

Creating a hierarchical tree in JavaScript and generating nested UL/LI output with ExpressJS

I have a piece of code from another request that is functioning properly. It creates a hierarchical tree with deep levels using JSON. However, I require the output to be in the form of an HTML UL/LI nested structure or a select menu for parent and child el ...

Ways to automatically close browser tab upon successful submission of a form

I have an old file that has been updated. One of the requirements for this file/project modification is to have the current browser window close when the user clicks OK to submit the form. I am curious if this can be done using plain/vanilla JavaScript? ...

JavaScript Array join() method returns an empty string

As a beginner in the world of javascript, I am just starting to dip my toes into it. In the past, I have used join() without any issues, but now I am facing a problem where this join is returning an empty string. Upon inspecting myArray, the data seems t ...

How can I extract specific data from a JSON response and populate a select dropdown with AngularJS?

My current project involves making an http.get request to fetch a list of airports. The JSON response is packed with information, presenting a series of objects in the format shown below {"id":"1","name":"Goroka","city":"Goroka","country":"Papua New Guine ...

Ways to retrieve a specific item from a constantly changing knockout observableArray without employing a foreach loop

Why can I only access one property ('member_A') of an Element in an observableArray using an HTML <input>? I am attempting to add a new object of type abc() to the observableArray "list_of_abc" when the button "ADD To List of abc" is click ...

Ways to show text on a donut chart when hovering with the mouse

I have been attempting to make adjustments to this sample. My goal is to display a word in the center of the donut chart upon mouseover, similar to this: https://i.sstatic.net/dCPKP.png Although I have included code for mouseover, it seems to not be func ...

What sets Angular 2 apart when it comes to utilizing [ngStyle] versus [style.attribute]?

When using Angular 2, what distinguishes the following 2 options for passing a variable value to a style? Are there advantages and disadvantages, or is it simply a matter of personal preference, or is one more adaptable/meant for specific purposes? Option ...

Sorting rows dynamically with jQuery Tablesorter

I've been struggling to find a solution for my specific issue. I need to have a static row in a large table that will not sort or move, allowing for repeated headers. Can anyone offer assistance with this? $("#dataTable").tablesorter({ ...

Displaying numerous database rows through SQL with the aid of PHP and JavaScript (specifically AJAX) on the frontend of a website

I am a beginner in the world of PHP and JavaScript (Ajax) and despite my efforts to find a solution by looking at various posts and websites, I have not been successful. My goal is to display all related database rows on the front end of a website. While ...

Guide on making a JavaScript button with both "light and dark" modes

Currently, I am attempting to change the color scheme of the page by adjusting the :root variables using a function called changeBackgrondColor(). This function is then assigned to the fontAwesome moon "button". However, when I click on the moon, the pag ...