Exploring ways to retrieve texture dimensions using Three.js

Can someone please advise me on how to retrieve the dimensions of a texture? I have set my texture using the following line of code:

const texture = THREE.ImageUtils.loadTexture(src)

Do I need to load the image in order to obtain its dimensions (and can this be done with JavaScript alone, without involving HTML and div elements)?

I want to ensure that the material I create will perfectly match the dimensions of the texture.

Answer №1

Recently, THREE.ImageUtils.loadTexture has been marked as deprecated in the latest version of THREE.js (r90). It is recommended to switch to using THREE.TextureLoader instead.

Once you have loaded a texture, you can access the image and its properties easily.

texture.image

If your image is in a known format, you can retrieve the dimensions using the width/height properties.

Keep in mind that loading a texture is asynchronous, so make sure to define an onLoad callback function.

var loader = new THREE.TextureLoader();
var texture = loader.load( "./img.png", function ( tex ) {
    // In this example, tex and texture are interchangeable
    console.log( tex.image.width, tex.image.height );
    console.log( texture.image.width, texture.image.height );
} );

Answer №2

If you disable sizeAttenuation and implement a function that resizes the Sprite based on the desired width, the code for this function would look like:

adjustSpriteWidth(width) {
     const texture = sprite.material.map;
     const scaleY = texture.image.height / texture.image.width;
     sprite.scale.setX(width).setY(width * scaleY);
}

This allows setting the scale based on the specified width while maintaining the image's aspect ratio.

In addition, it is necessary to have a function that takes in the camera as a parameter and adjusts the sprite's width based on the type of camera being used:

updateSpriteScale(camera) {
     let calculatedWidth = 1;
     if(camera.isOrthographicCamera) {
         calculatedWidth = camera.right - camera.left;
     }
     else if(camera.isPerspectiveCamera) {
         calculatedWidth = 2 * camera.aspect * Math.tan(camera.fov * 0.5 * 0.01745329);
     }
     adjustSpriteWidth(calculatedWidth * scaleFactor);
}

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

req.next does not exist as a function [END]

I am currently working on developing a website and I have encountered an issue in the dashboard stage. The error message TypeError: req.next is not a function keeps appearing, particularly when trying to create a subpage for the dashboard. I am utilizing t ...

Error found in Twitter Bootstrap popover plugin: `this.isHTML` function is missing

I took the example directly from their website: http://jsfiddle.net/D2RLR/631/ ... and encountered the following error: this.isHTML is not a function [Break On This Error] $tip.find('.popover-title')[this.isHTML(title) ? 'html&apos ...

Alter the entity type when passing it as a parameter

Trying to alter the Entity type, I am invoking a function that requires two parameters - one being the entity and the other a location. However, when trying to assign a Type for the first entity, it throws an error: Error: Argument of type 'Node<En ...

Include specific javascript files only for smartphones

Recently, I encountered an issue with a JavaScript code that swaps background images on scroll down. To address the problem with debounce, I ended up setting different debounce times for various browsers (I am aware this is not the ideal solution, but it&a ...

Utilize Vue.js methods to reverse the string within a paragraph using the appropriate function

Hello everyone, I've been attempting to implement a function to reverse a string within a paragraph text in vue.js. I've created a method called reverseword to reverse the words and added it to a card using :rule="reverseword()", but un ...

Experiencing Challenges with JavaScript Implementation Within an HTML Document

Code: <!DOCTYPE html> <head> <script type="text/javascript" src="jquery-3.3.1.js"> </script> <script type="text/javascript"> $(function() { alert("Hello World"); }); </script> <meta charset ...

Reconfigure the API to segment its components into individual variables

I'm currently working with an API that offers a wide range of available calls. In my VUE code, I am looking to modify it so that depending on which button is clicked, a different call is triggered. You can check out one example of this here: <> ...

A perfectly organized and justified menu with evenly spaced horizontal list items

I couldn't find a solution to evenly spacing out a series of list items for a menu styled list. After realizing CSS alone wasn't enough, I decided to incorporate some javascript (jQuery). My goal was to have equal padding between each LI without ...

Please input the number backwards into the designated text field

In my react-native application, I have a TextInput where I need to enter numbers in a specific order such as 0.00 => 0.01 => 0.12 => 1.23 => 12.34 => 123.45 and so on with each text change. I tried using CSS Direction "rtl" but it didn' ...

What is the best method to prevent next.js components from overlapping one another?

I recently created a website using next.js and noticed an issue in my index.js file. There is a div that houses the main components of the site: class Page extends Component { render() { return ( <div className={styles.container}> ...

Encountering a JSON parse error while utilizing the getJSON function

First time delving into coding with JavaScript and JSON, encountering an error message when using getJSON: parsererror SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data return window.JSON.parse( data ); Below is my code ...

The process of transferring information from a JSON API to TypeScript models

When working with my JSON API in my services, I need to pass the data to my models. What is the most efficient way to accomplish this task? Currently, I am following this process: import { Attachment } from '.'; export class Contact { id: nu ...

The process of utilizing variables to form objects in ES6

My ES5 code contains a variable as shown below. var options = { clientId : clientId, keepAlive : keepAlive, clean : clean, reconnectPeriod : reconnectPeriod, will : lastWillMessage }; If I want to convert this to ES6, I can do so by writing ...

Guide to deactivating scrolling on a specific element using jQuery

Can anyone provide a solution for disabling scroll on the window but still allowing scrolling within a text area? I attempted to use the following code, but it ended up disabling everything entirely: $('html, body').css({ overflow: 'hid ...

Contrasting the disparities between creating a new RegExp object using the RegExp constructor function and testing a regular

Trying to create a robust password rule for JavaScript using regex led to some unexpected results. Initially, the following approach worked well: const value = 'TTest90()'; const firstApproach = /^(?=(.*[a-z]){3,})(?=(.*[A-Z]){2,})(?=(.*[0-9]){2 ...

Utilizing fluent-ffmpeg in nodejs and express to effortlessly download a video

I've been recently tackling a side project that involves downloading videos from Reddit. The tricky part is that the video and audio are stored in separate files, requiring me to merge them before being able to download them onto the client's dev ...

Save a PHP variable and then use it on an HTML page

Is there a way to preserve the value of LAST_INSERT_ID(), also known as Case_ID, so that it can be accessed in another HTML page? If so, what would be the best approach to achieve this? $query.= "insert into Picture (Case_Pic,Case_ID) values ...

Retrieve a value from a PHP database table and transfer it to a different PHP webpage

I have values retrieved from a database and I need to select a row from a table and pass those values to the next PHP page, OInfo.php. I attempted to use Javascript to place those values in textboxes, but upon clicking the continue button, the values are n ...

Steps for populating a table with data from a JSON array

I am currently facing a challenge in populating an HTML table with data retrieved from a two-dimensional array. The information is being fetched through an $.ajax script after executing a php/MySQL query. Despite successfully parsing the data in the succes ...

How to create a donut chart in Highcharts without an inner pie section?

I've been scouring the internet in search of a solution to create a basic donut chart using the Highcharts library. Most examples I come across show donut charts with both an inner pie and outer donut (see here). Is there a way to remove the inner pi ...