javascript 三.js,如何访问场景内的项目?我应该使用 document.getElementById() 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16673937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Three.js, how to access items inside scene? Should I use document.getElementById()?
提问by Qrious
for ( var i = 0; i < 100; i ++ ) {
var particle = new THREE.Particle( new THREE.ParticleCanvasMaterial( { color: 0x666666, program: programStroke } ) );
particle.position.x = Math.random() * 800 - 400;
particle.position.y = Math.random() * 800 - 400;
particle.position.z = Math.random() * 800 - 400;
particle.scale.x = particle.scale.y = Math.random() * 10 + 10;
scene.add(particle);
scene.children[i].id = "q"+i; // to select item using document.getElementById();
}
projector = new THREE.Projector();
renderer = new THREE.CanvasRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
if(showStats == true){
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
container.appendChild( stats.domElement );
}
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
window.addEventListener( 'resize', onWindowResize, false );
console.log("1 -- "+scene);
console.log("2 -- "+scene.children);
console.log("3 -- "+document.getElementById('q1');
I tried to access the particles inside scene, so I pre-defined ids before adding them into scene. When I printed out scene.children, I could see their ids are like 'q0', 'q1', 'q2'.... However, document.getElementById() does not allow me to access those items.. In this case, how should I do it?
我试图访问场景内的粒子,所以我在将它们添加到场景之前预定义了 id。当我打印scene.children 时,我可以看到他们的id 像'q0'、'q1'、'q2'......但是,document.getElementById() 不允许我访问这些项目......在这种情况下,我该怎么办?
回答by gaitat
Instead of doing:
而不是做:
scene.children[i].id = "q"+i;
do:
做:
particle.name = "q"+i;
and then
接着
scene.traverse (function (object)
{
if (object instanceof THREE.Particle)
{
if (object.name === 'q10')
// do what you want with it.
}
});