[英]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?)?也许有必要加载图像以获得其尺寸(但是否只能使用 javascript,而不是 html 及其 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). 首先,
THREE.ImageUtils.loadTexture
在最新three.js所(R90)已过时。 Take a look at THREE.TextureLoader
instead. 看看
THREE.TextureLoader
。
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. 根据图像格式,您应该能够访问
width
/ height
属性,这将是纹理的尺寸。
Just a note: Loading a texture is asynchronous, so you'll need to define the onLoad
callback. 请注意:加载纹理是异步的,因此您需要定义
onLoad
回调。
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:如果您关闭 sizeAttenuation,并且您有一个 function 可以根据所需的宽度缩放 Sprite,那么这个 function 将类似于:
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.所以,此时,你可以根据想要的宽度来设置比例,保持图片的aspectRatio。
Then you must have a function that receives the camera, and depending on the type of camera, updates the sprite's width:然后你必须有一个 function 接收相机,并根据相机的类型更新精灵的宽度:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.