//创建场景 var scene = new THREE.Scene(); //透视摄像机(视野角度,长宽比,远剪切面,进剪切面,) var camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000); //渲染器 var renderer = new THREE.WebGLRenderer(); //设置渲染器的大小 renderer.setSize(window.innerWidth,window.innerHeight); //渲染器renderer的domElement元素,表示渲染器中的画布 document.body.appendChild(renderer.domElement); //创建几何体(长,宽,高) var geometry = new THREE.CubeGeometry(2,2,2); //材质增加颜色 var material = new THREE.MeshBasicMaterial({color:0x00ff00}); //网格(几何体,材质) var cube = new THREE.Mesh(geometry,material); //场景增加几何体 scene.add(cube); camera.position.z=5; function render(){ requestAnimationFrame(render); cube.rotation.x += 0.1; cube.rotation.y += 0.1; //渲染(场景,相机)render( scene, camera, renderTarget, forceClear ) //renderTarget:渲染的目标,默认是渲染到前面定义的render变量中 //forceClear:每次绘制之前都将画布的内容给清除,即使自动清除标志autoClear为false,也会清除 renderer.render(scene, camera); } render();
按照功能分解成函数
var renderer; function initThree(){ width = document.getElementById('canvas-frame').clientWidth; height = document.getElementById('canvas-frame').clientHeight; renderer = new THREE.WebGLRenderer({ antialias:true }); renderer.setSize(width,height); document.getElementById('canvas-frame').appendChild(renderer.domElement); renderer.setClearColor(0xffffff,1.0) } var camera; function initCamera(){ camera = new THREE.PerspectiveCamera(45,width/height,1,10000); camera.position.x=0; camera.position.y=1000; camera.position.z=0; camera.up.x=0; camera.up.y=0; camera.up.z=1; camera.lookAt({ x:0, y:0, z:0 }) } var scene; function initScene(){ scene = new THREE.Scene(); }; var light; function initLight(){ light = new THREE.DirectionalLight(0xff0000,1.0,0); light.position.set(100,100,200); scene.add(light); } var cube; function initObject(){ var geometry = new THREE.Geometry(); var material = new THREE.LineBasicMaterial({ vertexColors:THREE.VertexColors }); var color1= new THREE.Color(0x444444), color2= new THREE.Color(0xff0000); var p1 = new THREE.Vector3(-100,0,100); var p2 = new THREE.Vector3(100,0,-100); geometry.vertices.push(p1); geometry.vertices.push(p2); geometry.colors.push(color1,color2); var line = new THREE.Line(geometry,material,THREE.LinePieces); scene.add(line); } function render(){ renderer.clear(); renderer.render(scene,camera); requestAnimationFrame(render); } function threeStart(){ initThree(); initCamera(); initScene(); initLight(); initObject(); render(); } threeStart();