1

我正在用 WebGL 和 three.js 制作我的第一个动画。一切都很顺利,除了我的动画只在鼠标进入窗口时出现。

我的动画

我的代码:

var container = document.getElementById('container');
var wi       = window.innerWidth;
var he       = window.innerHeight;
var renderer  = new THREE.WebGLRenderer({
    antialias: true
});
var scene    = new THREE.Scene();
var camera   = new THREE.PerspectiveCamera(75,wi/he,1,10000);
var distance = 500;
var geometry2 = new THREE.Geometry();

renderer.setSize(wi ,he);
container.appendChild(renderer.domElement);
scene.add(camera);

var texture = THREE.ImageUtils.loadTexture( '/wp-content/themes/auriga-7/i/cloud.png' );
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;

var material = new THREE.MeshBasicMaterial( { map: texture,transparent: true} );
var plane = new THREE.PlaneGeometry( 400,400,4,8 );


for ( ix = 0; ix <100; ix++ ) {
item = new THREE.Mesh( plane, material );
item.position.x = ((Math.random()-0.5)*(Math.random() * wi/2) /4)*Math.random()*10;
item.position.y = ((Math.random()-0.5)*(Math.random() * he/2) /4)*Math.random()*10;
item.position.z = ix*10-50;
item.rotation.z = Math.random() *250;
item.scale.x = item.scale.y = Math.random() * Math.random() * 2 + 0.5;

THREE.GeometryUtils.merge(geometry2,item);
}

mesh = new THREE.Mesh( geometry2, material );
scene.add(mesh);


camera.position.z = distance;
camera.lookAt(scene.position);
renderer.sortObjects = false;


// create a point light
var pointLight =
  new THREE.PointLight(0xFFFFFF);

// set its position
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;

// add to the scene
scene.add(pointLight);
renderer.render(scene, camera);

document.addEventListener('mousemove',onMouseMove, false);
window.addEventListener('resize',onResizeMyFuckinBrowser,false);
function onMouseMove(event){

var mouseX = event.clientX - wi/2;
var mouseY = event.clientY - he/2;

camera.position.x = (mouseX - camera.position.x) * 0.02;
camera.position.y = (-mouseY - camera.position.y) * 0.02;
camera.position.z = distance;
camera.lookAt(scene.position);
renderer.render(scene, camera);
}
function onResizeMyFuckinBrowser(){
var wi       = window.innerWidth;
var he       = window.innerHeight;
renderer.setSize(wi ,he);
renderer.render(scene, camera);
}

我该如何解决这个问题?

4

1 回答 1

1

纹理加载是一个异步事件。最有可能的是,您render()在主程序中的调用发生在纹理加载之前。您的其他render()调用仅发生在鼠标移动事件和调整大小事件上。这就是为什么在移动鼠标之前什么都看不到的原因。

如果您不想使用requestAnimationFrame(),可以查看 的参数ImageUtils.loadTexture(),您将在其中看到回调函数的选项。您可以在回调中放置一个渲染调用。

于 2012-10-03T06:40:14.883 回答