1. 程式人生 > >three.js繪製網格

three.js繪製網格

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Three框架</title>
		<script src="../js/Three.js"></script>
		<style type="text/css">
			div#canvas-frame{
				border: none;
				cursor: pointer;
				width: 100%;
				height: 600px;
			}
		</style>
		<script>
			//建立渲染器
			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);
				//renderer.domElement 表示渲染器中的畫布,所有的渲染都是畫在domElement上面
				//appendChild表示將domElement掛接在 id為canvas-frame的div下面,
				document.getElementById('canvas-frame').appendChild(renderer.domElement);
				renderer.setClearColorHex(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;

				//up向量
				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();
				//幾何體中加入兩個頂點
				geometry.vertices.push(new THREE.Vector3(-500,0,0));
				geometry.vertices.push(new THREE.Vector3(500,0,0));

				for (var i=0;i<20;i++){
				    var line=new THREE.Line(geometry,new THREE.LineBasicMaterial({color:0x000000,opacity:0.2}));
				    line.position.z=(i*50)-500;
				    scene.add(line);

				    var line=new THREE.Line(geometry,new THREE.LineBasicMaterial({color:0x000000,opacity:0.2}));
				    line.position.x=(i*50)-500;
				    line.rotation.y=90*Math.PI/180;
				    scene.add(line);
				}

            }

            function threeStart() {
				initThree();
				initCamera();
				initScene();
				initLight();
				initObject();
				renderer.clear();
				renderer.render(scene,camera);
            }


		</script>
	</head>

	<body onload="threeStart();">
		<div id="canvas-frame"></div>
	</body>
</html>