2016-11-06 45 views
1

我有一個試圖映射圖像的立方體。我使用加載管理器加載圖像。我想知道爲什麼material.map以未定義的方式返回,也想知道我是否有縮放問題。原始圖像是512x512。箱子是20x20x20。Threejs textureLoader - 縮放和映射到網格

我遺漏了所有關於相機,渲染器等的代碼,但我試圖將它全部包含在下面的代碼片段/交互式部分中。

var loadingManager = new THREE.LoadingManager(); 

loadingManager.onProgress = function (item, loaded, total) { 

    //Loading percentage 
    console.log(loaded/total * 100 + '%'); 

} 

//Signify loading done 
loadingManager.onLoad = function() { 

    //Start the animation when the models are done loading 
    animate(); 
} 

function init() { 

    //create a loader 
    var loader2 = new THREE.TextureLoader(loadingManager); 

    //load the texture, and when it's done, push it into a material 
    loader2.load("../img/leo.jpg", function (texture) { 

    //do I need to do this? 
    texture.wrapS = texture.wrapT = THREE.RepeatWrapping 
    texture.repeat.set(boxSize, boxSize) 

    //why is this texture not coming through? 
    console.log(texture) 

    //does not work: 
    material1 = new THREE.MeshBasicMaterial({ 
     map: texture, 
     side: THREE.DoubleSide 
    }); 


    }) 

    var geo = new THREE.BoxGeometry(30, 30, 30) 
    var mat = new THREE.MeshBasicMaterial({ 
    color: 0xb7b7b7 
    }) 
    mesh = new THREE.Mesh(geo, material1) 
    scene.add(mesh) 

} 

// This works, so I know the image path is correct 
var img = document.createElement('img'); 
img.src = '../img/leo.jpg'; 
document.getElementById('container').appendChild(img); 

從控制檯日誌質感的值是這樣的: enter image description here

enter image description here

+0

你有沒有嘗試添加一個斷點定義時'material1'?那條線上的'texture'的價值是什麼?當你沒有預期的行爲時,調試是至關重要的。 – Marcs

+0

謝謝@Marcs - 我添加了一個控制檯日誌的屏幕抓圖。我添加了一個調試器並對其進行了檢查。任何想法,鑑於材料內的圖像是空的? – EJW

+0

如果您需要外部庫,請不要擔心該代碼片段不方便,您可以將其刪除,也可以將其刪除。 – Marcs

回答

1

錯誤是相關的事實,你是材料的load功能的回調以外的關聯你的裝載器,你必須在回調中做到這一點。

從文檔TextureLoader

  • onLoad - 加載完成時將被調用。

你要做如下:

loader2.load("../img/leo.jpg", function(texture) { 
     texture.wrapS = texture.wrapT = THREE.RepeatWrapping 
     texture.repeat.set(boxSize,boxSize) 
     //why is this texture 1 not coming through? 
     console.log(texture) 

     //neither of these work: 
     var geo = new THREE.BoxGeometry(30,30,30); 
     material1 = new THREE.MeshBasicMaterial({ map: texture,side: THREE.DoubleSide }); 

     var mesh = new THREE.Mesh(geo, material1); 

     // animation loop 
     function animate() { 

     requestAnimationFrame(animate); 

     render(); 

     // update stats 
     stats.update(); 
     } 

     ... 
}); 

爲了使這個更具可讀性和避免回調惡夢做這樣的事情:

function myInit(texture) { 
    ... 
} 

loader2.load("../img/leo.jpg", myInit); 
+0

謝謝@Marcs!是的,我想我的代碼太雜亂了。這完全保存了它!我很困難,再次感謝你抽出時間。 – EJW

+0

樂於幫助@EJW。請記住,在JavaScript中,您必須在加載或訪問外部資源時考慮回調。 – Marcs