three.js 场景入门
<!DOCTYPE html> <html> <head> <title>Example 01.02 - First Scene</title> <script type="text/javascript" src="../libs/three.js"></script> <script type="text/javascript" src="../libs/jquery-1.9.0.js"></script> <style> body{ /* set margin to 0 and overflow to hidden, to go fullscreen */ margin: 0; overflow: hidden; } </style> </head> <body> <!-- Div which will hold the Output --> <div id="WebGL-output"> </div> <!-- Javascript code that runs our Three.js examples --> <script type="text/javascript"> // once everything is loaded, we run our Three.js stuff. $(function () { // create a scene, that will hold all our elements such as objects, cameras and lights. var scene = new THREE.Scene(); // create a camera, which defines where we're looking at. var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000); // create a render and set the size var renderer = new THREE.WebGLRenderer(); renderer.setClearColorHex(0xEEEEEE);//渲染器背景颜色:白色 renderer.setSize(window.innerWidth, window.innerHeight);//渲染场景的尺寸 var axes = new THREE.AxisHelper( 20 );//创建一个axes(坐标轴)对象 scene.add(axes);//用scene.add()函数将坐标轴添加到场景中 // create the ground plane 创建场景 var planeGeometry = new THREE.PlaneGeometry(60,20);//定义平面的尺寸,宽60,高20 var planeMaterial = new THREE.MeshBasicMaterial({color: 0xcccccc});//定义平面的外观 如颜色,透明度,这里我们创建了一个基本的材质MeshBasicMaterial()方法,还有颜色 var plane = new THREE.Mesh(planeGeometry,planeMaterial);//把这两个对象合并到一个名为plane的网格中 // rotate and position the plane 绕x轴旋转90度然后通过设置位置属性定义它在场景中的位置。 plane.rotation.x=-0.5*Math.PI; plane.position.x=15 plane.position.y=0 plane.position.z=0 // add the plane to the scene scene.add(plane);//把plane添加到scene // create a cube 方块 var cubeGeometry = new THREE.CubeGeometry(4,4,4); var cubeMaterial = new THREE.MeshBasicMaterial({color: 0xff0000, wireframe: true});//线框属性:true var cube = new THREE.Mesh(cubeGeometry, cubeMaterial); // position the cube cube.position.x=-4; cube.position.y=3; cube.position.z=0; // add the cube to the scene scene.add(cube); //create a sphere 球体 var sphereGeometry = new THREE.SphereGeometry(4,20,20); var sphereMaterial = new THREE.MeshBasicMaterial({color: 0x7777ff, wireframe: true}); var sphere = new THREE.Mesh(sphereGeometry,sphereMaterial); // position the sphere sphere.position.x=20; sphere.position.y=4; sphere.position.z=2; // add the sphere to the scene scene.add(sphere); // position and point the camera to the center of the scene指定相机的位置,即悬挂在场景的上方,以确保我们能够拍摄到这些物体 camera.position.x = -30; camera.position.y = 40; camera.position.z = 30; camera.lookAt(scene.position);//使用lookat()函数指向场景的中心 // add the output of the renderer to the html element $("#WebGL-output").append(renderer.domElement);//使用jQuery来选择正确的输出元素 // render the scene renderer.render(scene, camera);//并告诉渲染器使用相机把场景渲染出来 }); </script> </body> </html>