要开发web3D的项目,大名鼎鼎的threejs相信你一定听说过。接下来,我们就按照国际惯例,从helloworld开始,把大家带入3D的世界!
首先我们从GitHub(https://github.com/mrdoob/three.js/)下载three.min.js,其实可以download他们所有的库,里面还包含很多例子,这里我们仅仅使用在build目录下的已经打包好的three主文件,然后在html里面引用好threejs的库
<script src="js/three.min.js"></script>
然后引入场景控制辅助类(在源码包的example/js/controls里面)
<script src="js/OrbitControls.js"></script>
接着在JS代码中写入以下代码
var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 ); camera.position.set(5,5,5); var renderer = new THREE.WebGLRenderer({antialias: true }); renderer.setSize( window.innerWidth, window.innerHeight ); renderer.setClearColor(0x177FB3,1); document.body.appendChild( renderer.domElement ); var geometry = new THREE.BoxGeometry( 1, 1, 1 ); var material = new THREE.MeshBasicMaterial( { color:0xff5678 } ); var cube = new THREE.Mesh( geometry, material ); scene.add( cube ); var controls = new THREE.OrbitControls(camera , renderer.domElement); var render = function () { requestAnimationFrame( render ); renderer.render(scene, camera); }; render();
最终的完整html代码如下:
<html> <head> <title>Three.js Hello World</title> <style> body { margin: 0; } canvas { width: 100%; height: 100% } </style> <script src="js/three.min.js"></script> <script src="js/OrbitControls.js"></script> </head> <body> <script> var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 ); camera.position.set(5,5,5); var renderer = new THREE.WebGLRenderer({antialias: true }); renderer.setSize( window.innerWidth, window.innerHeight ); renderer.setClearColor(0x177FB3,1); document.body.appendChild( renderer.domElement ); var geometry = new THREE.BoxGeometry( 1, 1, 1 ); var material = new THREE.MeshBasicMaterial( { color:0xff5678 } ); var cube = new THREE.Mesh( geometry, material ); scene.add( cube ); var controls = new THREE.OrbitControls(camera , renderer.domElement); var render = function () { requestAnimationFrame( render ); renderer.render(scene, camera); }; render(); </script> </body> </html>
最终效果如下,你可以使用鼠标旋转立方体哦