为THREEJS场景添加光影效果
添加光影效果主要用到的代码如下:
//使渲染器支持阴影贴图 THREE.Render.shadowMapEnabled= true; //设置灯光阴影属性 //设置灯光生成阴影 THREE.Light.castShadow= true; //如果是调试状态,还可以把灯光的调试帮助框显示出来 THREE.Light.shadowCameraVisible= true; //设置阴影贴图质量 THREE.Light.shadowMapWidth = THREE.Light.shadowMapHeight = 1024*4; //设置模型属性 //设置物体生成阴影 THREE.Mesh.castShadow = true; //设置物体接收阴影,即其它物体的阴影可以显示在该物体上 THREE.Mesh.receiveShadow= true;
完整的测试代码如下:
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script src="ThreeJS/build/three.js"></script> <script src="ThreeJS/examples/js/controls/OrbitControls.js"></script> <script src="ThreeJS/examples/js/loaders/OBJMTLLoader.js"></script> <script src="ThreeJS/examples/js/loaders/MTLLoader.js"></script> <script> var _scene,_camera,_control,_render,_ambient,_spotLight; Init(); Animate(); function Init() { _scene = new THREE.Scene(); _camera = new THREE.PerspectiveCamera(45,window.innerWidth/window.innerHeight,0.1,2000); _camera.position.z = 50; _render = new THREE.WebGLRenderer(); //设置渲染器大小 _render.setSize(window.innerWidth,window.innerHeight); //设置渲染器阴影可用 _render.shadowMapEnabled = true; document.body.appendChild(_render.domElement); //场景控制器,用以控制场景中的摄相机,方便观察场景 _control = new THREE.OrbitControls(_camera,_render.domElement); //添加环境光 _ambient = new THREE.AmbientLight(0xffffff); _scene.add(_ambient); //灯光属性 _spotLight = new THREE.SpotLight(0xffffff); _spotLight.castShadow = true; _spotLight.shadowCameraVisible = true; _spotLight.position.set(100,100,100); //设置阴影贴图精度 _spotLight.shadowMapWidth = _spotLight.shadowMapHeight = 1024*4; _scene.add(_spotLight); //加载模型 LoadModel(); } function Animate() { requestAnimationFrame(Animate); Render(); } function Render() { //更新摄相机角度 _control.update(); _render.render(_scene,_camera); } function LoadModel() { //调用OBJMTLLoader加载模型 var loader = new THREE.OBJMTLLoader(); loader.load(‘Model/tc_tm/tc.obj‘,‘Model/tc_tm/tc.mtl‘, function(obj) { //traverse:回调,该模型以及所有子模型均执行该函数 //相当于遍历obj的children数组 obj.traverse(function(child) { if (child instanceof THREE.Mesh) { //设置模型生成阴影并接收阴影 child.castShadow = true; child.receiveShadow = true; } }); _scene.add(obj); }); } </script> </body> </html>
效果如下图所示:
远观:
近看:
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。