2013-02-23 83 views
1

我想使用three.js所庫,它是一個JavaScript 3D庫...javascript代碼不工作

因此,代碼片段是這樣的:

var segments = 16, rings = 16; 
//var radius = 50; <-- original 

// create a new mesh with sphere geometry - 
// we will cover the sphereMaterial next! 
var scene = new THREE.Scene(); 
// My read from file snippet. 
$.getJSON('sample.json', function(data) { 
    var radius = data.circles.r; 
    console.log(radius); 


    var sphere = new THREE.Mesh(
     new THREE.SphereGeometry(radius, segments, rings), 
     sphereMaterial); 

    // add the sphere to the scene 
    scene.add(sphere); 
}); 
// and the camera 
scene.add(camera); 

所以基本上早些時候代碼..半徑硬編碼(第二行),而不是硬編碼半徑..我正在從json文件中讀取它正在跟蹤?

{ 
"circles": 

{"x":14,"y":2,"z":4,"r":20} 
} 

但它不顯示任何東西?而且我在螢火蟲中也看不到任何錯誤 有什麼建議嗎? 謝謝

+0

它是否直接爲您工作,沒有JSON調用? – 2013-02-23 22:14:14

回答

1

$.getJSON(...)的調用是異步的。所以聲明的順序很可能是

  1. var scene = new THREE.Scene();
  2. scene.add(camera);
  3. var sphere = new THREE.Mesh(...);
  4. scene.add(sphere);

如果您將scene.add(camera);移動到您的成功函數中,它應該像以前一樣工作。

+0

謝謝..它不工作。我收到一條警告:「DEPRECATED:攝像頭沒有被添加到場景中,將它添加到...」 什麼是正確的方式讓這個東西讀取數據並將其作爲參數傳遞? – user2052251 2013-02-23 21:34:22

+0

@ user2052251更改爲'getJSON'之前的順序是什麼? – 2013-02-23 21:35:36

+0

http://jsfiddle.net/26PZg/ – user2052251 2013-02-23 21:45:55