前面学习了一些webgl的基础知识,现在就用一下three.js写一个小例子,记录一下学习的过程。
效果图:
1.去github下载three.js,然后将它加载到网页中
<script src="js/three.js"></script>
2接着就该写一下参数了,主要的四大组件一个不能少
2.1生成“场景”组件
var scene = new THREE.Scene();
2.2生成“相机”组件
var camera = new THREE.PerspectiveCamera(45 , window.innerWidth/window.innerHeight, 1, 1000);
四个参数
第一个参数:是夹角
第二个参数:宽高比
第三个参数:最近距离
第四个参数:最远距离
2.3生成“渲染器”组件
var renderer = new THREE.WebGLRenderer();
因为渲染器有许多种,按需求生成
2.4生成“几何体”组件
var geometry = new THREE.CubeGeometry(2,2,2);
这里生成了一个立方体,同样也可以生成多种几何体
3.最后渲染出图形
function render(){ //add animation requestAnimationFrame(render); //rotating cube.rotation.x += 0.01; cube.rotation.y += 0.01; //renderer cube renderer.render(scene,camera); }
其中requestAnimationFrame是新的方法,也可以用setTimeout 代替
详细代码:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script src="js/three.js"></script> </head> <body> <script> //create scenc var scene = new THREE.Scene(); //create Camera var camera = new THREE.PerspectiveCamera(45 , window.innerWidth/window.innerHeight, 1, 1000); //create renderer var renderer = new THREE.WebGLRenderer(); //clean renderer color renderer.setClearColor('#FFFFFF'); //set renderer size renderer.setSize(window.innerWidth,window.innerHeight); //put rendererDom into body document.body.appendChild(renderer.domElement); //create geometry var geometry = new THREE.CubeGeometry(2,2,2); //create naterial var material = new THREE.MeshBasicMaterial({color:0xff0000}); //create cube var cube = new THREE.Mesh(geometry,material); //put cube into scene scene.add(cube); //Point of view see the cube camera.position.z = 10; function render(){ //add animation requestAnimationFrame(render); //rotating cube.rotation.x += 0.01; cube.rotation.y += 0.01; //renderer cube renderer.render(scene,camera); } render(); </script> </body> </html>
学习资料:
[1]:WebGL中文网:http://www.hewebgl.com
[2]:three.js在Github地址:https://github.com/Billshuai/three.js
[3]:一些案例:https://threejs.org/
[4]:易百webgl教程:http://www.yiibai.com/webgl/webgl_context.html