簡體   English   中英

如何使用 Three.js 獲取紋理尺寸

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM