简体   繁体   中英

How to get texture dimensions with Three.js

I would like to know wether it is possible to get the dimensions of a texture? I used this line to set my texture:

const texture = THREE.ImageUtils.loadTexture(src)

Maybe it is necessary to load the image to get its dimensions (but is it possible only with javascript, not html and its div?)?

I would like the material I create afterwards to fit the texture dimensions.

First, THREE.ImageUtils.loadTexture is deprecated in the latest THREE.js (r90). Take a look at THREE.TextureLoader instead.

That said, you can get to the image and its properties from a loaded texture.

texture.image

Depending on the image format, you should be able to access the width / height properties, which will be your texture's dimensions.

Just a note: Loading a texture is asynchronous, so you'll need to define the onLoad callback.

var loader = new THREE.TextureLoader();
var texture = loader.load( "./img.png", function ( tex ) {
    // tex and texture are the same in this example, but that might not always be the case
    console.log( tex.image.width, tex.image.height );
    console.log( texture.image.width, texture.image.height );
} );

If you turn off sizeAttenuation, and you have a function that scales the Sprite according to the desired width, then this function will be like:

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

So, at this point, you can set the scale according to the desired width, maintaining the aspectRatio of the image.

Then you must have a function that receives the camera, and depending on the type of camera, updates the sprite's width:

updateScale(cam) {
     let cw = 1;
     if(cam.isOrthographicCamera) {
         cw = cam.right - cam.left;
     }
     else if(cam.isPerspectiveCamera) {
         cw = 2 * cam.aspect * Math.tan(cam.fov * 0.5 * 0.01745329);
     }
     scaleWidth(cw * desiredScaleFactor);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM