THREE.js学习记录
前言
一直自己没有学习做笔记的习惯,所以为了加强自己对知识的深入理解,决定将学习笔记写下来,希望向各位大牛们学习交流!
不当之处请斧正!在此感谢!
大牛们对此文可以忽略!
硬推:欢迎大家访问我的个人网站www.zsy.ink(不适合手机端访问)
three.js
什么是threejs,很简单,你将它理解成three + js就可以了。three表示3D的意思,js表示javascript的意思。那么合起来,three.js就是使用javascript 来写3D程序的意思。
源自:
github:https://github.com/mrdoob/three.js
官网:https://threejs.org/
ps:有些问题国内搜不到就去github/StackOverflow/google(需要番·羽·土·啬)
用three.js在网页上制作旋转立方体
效果如下:
实现代码如下:
<!DOCTYPE html>
<html>
<head>
<title>three.js</title>
<style>
body {
margin: 0px;
overflow: hidden;
}
</style>
<script src="three.js-master/build/three.js"></script>
<!-- 路径根据具体开发环境而定 -->
</head>
<body>
<!-- three.js输出节点 -->
<div id="three.js"></div>
<!-- three.js代码 -->
<script type="text/javascript">
var scene, camera, render, cube; //声明全局变量
init(); //调用函数
animate(); //调用函数
function init() {
scene = new THREE.Scene(); //生成一个场景
scene.background = new THREE.Color( 0x02547d ); //设置场景背景颜色
//生成一个透视相机
camera = new THREE.PerspectiveCamera(45,window.innerWidth/window.innerHeight,0.1,1000);
// 相机参数分别为视角↑, 长宽比↑, 近面↑,远面↑
//调整相机位置
camera.position.x=0;
camera.position.y=20;
camera.position.z=40;
camera.lookAt(scene.position); //相机镜头对准场景
//生成一个WebGl渲染器
render = new THREE.WebGLRenderer({antialias:true}); //参数:抗锯齿
render.setSize(window.innerWidth,window.innerHeight);
render.shadowMapEnabled=true; //允许阴影映射,渲染阴影默认是关闭的,因为会消耗大量资源
render.shadowMap.type = THREE.PCFSoftShadowMap; //使渲染阴影更精细,不然会马赛克
var planeGeometry=new THREE.PlaneGeometry(200,200,10,10); //生成一个平面
//生成一个材质
var planeMaterial=new THREE.MeshLambertMaterial({color:0x0284a8});
//生成一个网格,将平面和材质放在一个网格中,组合在一起,组成一个物体
var plane=new THREE.Mesh(planeGeometry,planeMaterial);
plane.rotation.x=-0.5*Math.PI; //将平面沿着x轴进行旋转
plane.position.x=0;
plane.position.y=0;
plane.position.z=20;
plane.receiveShadow=true; //平面进行接受阴影
var cubeGeometry=new THREE.BoxGeometry(10,10,10); //生成一个立方体
//生成一个材质
var planeMaterial1=new THREE.MeshBasicMaterial({color:0x02bec4});
cube = new THREE.Mesh(cubeGeometry,planeMaterial1);
//plane1.rotation.x=-0.5*Math.PI;//将平面沿着x轴进行旋转
cube.position.x=0;
cube.position.y=6;
cube.position.z=0;
cube.castShadow=true; //需要阴影,方块进行投射阴影
var spotLight=new THREE.SpotLight(0xffffff); //生成一个聚光灯光源
spotLight.position.set(-10,30,-5); //设置聚光灯光源位置
spotLight.angle = 2; //聚光灯角度
spotLight.castShadow=true; //聚光灯光源允许阴影映射
spotLight.shadow.mapSize.width = 2048; //设置阴影精度,不然会马赛克
spotLight.shadow.mapSize.height = 2048; //设置阴影精度,不然会马赛克
//将相机,渲染器,平面,立方体,聚光灯光源都添加到场景中,然后对场景和相机进行渲染
scene.add(camera);
scene.add(render);
scene.add(plane);
scene.add(cube);
scene.add(spotLight);
render.render(scene,camera);
document.getElementById("three.js").append(render.domElement);
};
//每一帧渲染一次画面,不然画面是静止
function animate() {
requestAnimationFrame(animate); //回调函数
cube.rotation.y += 0.01; //让立方体每一帧都旋转
render.render(scene, camera); //渲染
}
</script>
</body>
</html>