单击three.js中的链接旋转球体

时间:2016-04-14 12:15:16

标签: javascript three.js

我创建了一个球体,我有一组链接。我想通过单击任何链接来更改球体的位置或旋转球体。我试图搜索很多,但找不到任何类似的例子。

1 个答案:

答案 0 :(得分:0)

这只是创建一个HTML元素并将JS函数与其“onclick”事件相关联的问题。这是基本场景的快速实现,使用按钮(您可以用链接或任何您喜欢的内容替换它):

<强> HTML

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Rotate Mesh On Button Clicked</title>
    </head>

    <body>

        <button onclick="myFunction()">Rotate</button>


        <script type="text/javascript" src="three.min.js"></script>
        <script type="text/javascript" src="OrbitControls.js"></script>

        <script type="text/javascript" src="scene.js"></script>

    </body>

</html>

<强>的JavaScript

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

 var cameraControls;

init();
animate();

function init() {

    container = document.createElement( 'div' );
    document.body.appendChild( container );

    // renderer

    renderer = new THREE.WebGLRenderer( { antialias: true } );
    renderer.setSize( window.innerWidth, window.innerHeight );
    renderer.setClearColor( 0xdbdbdb );
    container.appendChild( renderer.domElement );

    // scene

    scene = new THREE.Scene();

    // camera

    camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 1, 10000 );
    camera.position.set( 3, 0.5, 40 );
    scene.add( camera ); 

    // controls
    cameraControls = new THREE.OrbitControls( camera, renderer.domElement );

    // lights

    scene.add( new THREE.AmbientLight( 0x222222 ) );

    var light = new THREE.PointLight( 0xffffff, 0.8 );
    camera.add( light );

    // objects

    geometry = new THREE.CylinderGeometry( 5, 5, 5, 5 );

    material = new THREE.MeshPhongMaterial(  {color: 0x00aafa} );

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



    scene.add( mesh );

    window.addEventListener( 'resize', onWindowResize, false );

}

function myFunction() {

    mesh.rotateX(90);
}

function onWindowResize() {

    camera.aspect = window.innerWidth / window.innerHeight;

    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );

}

function animate() {

    requestAnimationFrame( animate );

    render();

    cameraControls.update();

}

function render() {

    camera.lookAt( scene.position );

    renderer.render( scene, camera );

}

正如您所看到的,当单击该按钮时,它会调用“myFunction”,它将网格旋转90°,非常简单。