[英]How to get texture dimensions with Three.js
我想知道是否可以获得纹理的尺寸? 我用这一行来设置我的纹理:
const texture = THREE.ImageUtils.loadTexture(src)
也许有必要加载图像以获得其尺寸(但是否只能使用 javascript,而不是 html 及其 div?)?
我希望我之后创建的材料适合纹理尺寸。
首先, THREE.ImageUtils.loadTexture
在最新three.js所(R90)已过时。 看看THREE.TextureLoader
。
就是说,您可以从加载的纹理获取图像及其属性。
texture.image
根据图像格式,您应该能够访问width
/ height
属性,这将是纹理的尺寸。
请注意:加载纹理是异步的,因此您需要定义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 );
} );
如果您关闭 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);
}
所以,此时,你可以根据想要的宽度来设置比例,保持图片的aspectRatio。
然后你必须有一个 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.