• 微信公众号：美女很有趣。 工作之余，放松一下，关注即送10G+美女照片！

2小时前 1次浏览

# Three.js简单的旋转示例

``````//引入three.js 库
<script src="js/three.js"></script>
<body>
<!-- 将在div里面输出画面 -->
<div id="threejs-output"></div>
</body>
<script>
//具体three.js的代码
</script>
``````

## 分步分析一下几个关键核心的代码：

### 1.场景scene

``````var scene = new THREE.Scene();
``````

``````// 显示三维坐标系
var axes = new THREE.AxisHelper(20)
// 添加坐标系到场景中
``````

### 2.相机Camera

``````var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 2000)
``````
``````// 定位相机，并且指向场景中心
camera.position.x = 30;
camera.position.y = 30;
camera.position.z = 30;
camera.lookAt(scene.position)
``````

### 3.渲染器renderer

``````var renderer = new THREE.WebGLRenderer();
``````
``````// 设置渲染器的初始颜色
renderer.setClearColor(new THREE.Color(0xeeeeee));
// 设置输出canvas画面的大小
renderer.setSize(window.innerWidth, window.innerHeight)
// 设置渲染物体阴影
``````
``````// 将渲染器输出添加html元素中
document.getElementById('webgl-output').appendChild(renderer.domElement);
renderer.render(scene, camera)
``````

### 4.几何体Geometry 和 材质Material

``````//添加立方体
var boxGeometry = new THREE.BoxGeometry(4, 4, 4);

var cubeMaterial = new THREE.MeshLambertMaterial({
color: 0xff0000
})
var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
cube.position.x = 0;
cube.position.y = 4;
cube.position.z = 2;
// 对象是否渲染到阴影贴图当中
``````

### 5.光源Light

``````// 创建聚光灯
var spotLight = new THREE.SpotLight(0xFFFFFF);
spotLight.position.set(130, 130, -130);
spotLight.angle = Math.PI / 4;
// 添加聚光灯
``````

### 6.动效和鼠标控制

``````let T1 =new Date()
function render() {
let T2 =new Date()
let t = T2-T1;
renderer.render(scene, camera)
// 绕y轴0.01弧度
cube.rotateY(0.01)
window.requestAnimationFrame(render)
}

//循环请求动画帧
window.requestAnimationFrame(render)

// 创建controls对象;
var controls = new THREE.OrbitControls(camera, renderer.domElement)
// 监听控制器的鼠标事件，执行渲染内容