Three.js简单的旋转示例
感谢:b站老陈
//引入three.js 库
<script src="js/three.js"></script>
<body>
<!-- 将在div里面输出画面 -->
<div id="threejs-output"></div>
</body>
<script>
//具体three.js的代码
</script>
window.onload() 方法用于在网页加载完毕后立刻执行的操作,即当 HTML 文档加载完毕后,立刻执行某个方法。
做一个简单的示例:
分步分析一下几个关键核心的代码:
1.场景scene
var scene = new THREE.Scene();
将某个元素加入到场景中(如坐标系)
// 显示三维坐标系
var axes = new THREE.AxisHelper(20)
// 添加坐标系到场景中
scene.add(axes);
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)
// 设置渲染物体阴影
renderer.shadowMapEnabled = true;
// 将渲染器输出添加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;
// 对象是否渲染到阴影贴图当中
cube.castShadow = true;
scene.add(cube)
添加球体类似
5.光源Light
// 创建聚光灯
var spotLight = new THREE.SpotLight(0xFFFFFF);
spotLight.position.set(130, 130, -130);
spotLight.castShadow = true;
spotLight.angle = Math.PI / 4;
spotLight.shadow.penumbra = 0.05
spotLight.shadow.mapSize.width = 1024;
spotLight.shadow.mapSize.innerHeight = 1024;
// 添加聚光灯
scene.add(spotLight)
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)
// 监听控制器的鼠标事件,执行渲染内容
controls.addEventListener('change', () => {
renderer.render(scene, camera)
})