如何在click事件处理程序中将对象添加到three.js场景?

时间:2013-08-17 21:46:38

标签: javascript three.js

如果在文档就绪时初始化了一个three.js场景,当init()函数已经触发后用户触发click事件时,如何添加3D对象(如简单的多维数据集)?

这是已经有场景设置的fiddle

var camera, scene, renderer;
var geometry, material, mesh;

window.addEventListener("click", onClick, false);


function onClick() {
    alert("Replace me with code to add an object!");
}

var init = function () {

    renderer = new THREE.CanvasRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000);
    camera.position.z = 500;

    scene = new THREE.Scene();

geometry = new THREE.CubeGeometry(200, 200, 200);
material = new THREE.MeshBasicMaterial({
                color: 0x000000,
                wireframe: true,
                wireframeLinewidth: 2
            });

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

}

var animate = function () {

    requestAnimationFrame(animate);

    mesh.rotation.x = Date.now() * 0.0005;
    mesh.rotation.y = Date.now() * 0.001;

    renderer.render(scene, camera);

}

init();
animate();

2 个答案:

答案 0 :(得分:5)

获取元素ID

var el = document.getElementById("element-id");

添加活动

el.addEventListener("click", addCube, false);


function addCube(){
   var geometry = new THREE.CubeGeometry( 200, 200, 200 );

   var material = new THREE.MeshBasicMaterial( { color: 0x000000 } );

   var mesh = new THREE.Mesh( geometry, material );

  //scene is global
   scene.add(mesh);
}

或者使用jquery

$(element).click(addCube);

答案 1 :(得分:1)

这里是一个带有旋转的动态添加立方体的小提琴:

function addCube(){
         var r = Math.random() + 0.5;
     var geometry = new THREE.CubeGeometry( 200 * r, 200 * r, 200 * r);

     var material = new THREE.MeshBasicMaterial( { color: 0x00FF00,
                wireframe: true,
                wireframeLinewidth: 2 } );
                var mtmp = new THREE.Mesh( geometry, material );
        meshes.push( mtmp );

    //scene is global
        scene.add(mtmp);


  }
var animate = function () {

     requestAnimationFrame(animate);

      for (var i = 0; i < meshes.length; i++) {
        console.log(i);
        //scene.add(meshes[i]);
        meshes[i].rotation.x = Date.now() * 0.0005 * (1+i);
                meshes[i].rotation.y = Date.now() * 0.001 * (1+i);
      }


            renderer.render(scene, camera);
    }

http://jsfiddle.net/Lkk1zhkt/2/