index.html文件:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>Cube</title> 6 <script type="text/javascript" src="three.js"></script> 7 <script type="text/javascript" src="mythree.js"></script> 8 <script type="text/javascript" src="js/controls/OrbitControls.js"></script> 9 </head> 10 11 <body onload="init()"> 12 <div> 13 <canvas id="mainCanvas" width="500px" height="500px" ></canvas> 14 </div> 15 </body> 16 17 </html>
mythere.js文件:
1 var renderer, camera, scene,cube,controls; 2 3 function init() { 4 // renderer 5 renderer = new THREE.WebGLRenderer({ 6 canvas: document.getElementById(‘mainCanvas‘) 7 }); 8 renderer.setClearColor(0x000000); // black 9 // scene 10 scene = new THREE.Scene(); 11 // camera 12 camera = new THREE.PerspectiveCamera(45, 4 / 3, 1, 1000); 13 camera.position.set(0, 0, 5); 14 scene.add(camera); 15 // a cube in the scene 16 cube = new THREE.Mesh(new THREE.CubeGeometry(2, 2, 3), 17 new THREE.MeshBasicMaterial({ 18 color: 0xff0000 19 }) 20 ); 21 scene.add(cube); 22 23 //controlls 24 controls = new THREE.OrbitControls( camera ); 25 controls.addEventListener( ‘change‘, render ); 26 27 // Animation 28 requestAnimationFrame(draw); 29 30 render(); 31 } 32 33 // Animation 34 function draw() { 35 id = requestAnimationFrame(draw); 36 cube.rotation.x += 0.05; 37 cube.rotation.y += 0.05; 38 renderer.render(scene, camera); 39 } 40 41 function render() { 42 renderer.render(scene, camera); 43 }