1.three.js的引入
进入官网Three.js – JavaScript 3D Library,下载文件
解压文件,复制three.js-master\build\three.min.js文件
在项目中,引入该文件。
2.一个简单threeJs程序
(1)创建场景
const scene = new THREE.Scene();
(2)创建物体
const geomtry = new THREE.BoxGeometry(1, 1, 1); // 创建几何体
const material = new THREE.MeshBasicMaterial(); // 创建材质
const cube = new THREE.Mesh(geomtry, material); // 将几何体和材质绑定到一起,创建物体
scene.add(cube); // 将物体添加到场景中
(3)创建光源
const light = new THREE.AmbientLight();
scene.add(light);
(4)创建相机
const camera = new THREE.PerspectiveCamera(75, w / h, 0.1, 100); // 创建相机 参数(相机的角度范围 宽高比值 相机最近能看多近 相机最远能看到多远)
camera.position.set(0, 0, 5); // 相机的位置
camera.lookAt(0, 0, 0) ;// 相机的朝向
(5)创建渲染器
const renderer = new THREE.WebGLRenderer(); //创建渲染器
renderer.setSize(w, h);// 向渲染器传递宽高
renderer.render(scene, camera);// 向渲染器传递场景和相机
(6)设置可视的范围
const w = window.innerWidth;
const h = window.innerHeight;
(7)给html页面添加3D查看元素
document.body.append(renderer.domElement);
(0)完整代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/three.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
body {
overflow: hidden;
}
</style>
</head>
<body>
<script>
const w = window.innerWidth;
const h = window.innerHeight;
// 创建场景
const scene = new THREE.Scene();
// 创建物体
const geomtry = new THREE.BoxGeometry(1, 1, 1); // 创建几何体
const material = new THREE.MeshBasicMaterial(); // 创建材质
const cube = new THREE.Mesh(geomtry, material); // 将几何体和材质绑定到一起,创建物体
scene.add(cube); // 将物体添加到场景中
// 创建光源
const light = new THREE.AmbientLight();
scene.add(light);
// 创建相机
const camera = new THREE.PerspectiveCamera(75, w / h, 0.1, 100); // 创建相机 参数(相机的角度范围 宽高比值 相机最近能看多近 相机最远能看到多远)
camera.position.set(0, 0, 5); // 相机的位置
camera.lookAt(0, 0, 0) ;// 相机的朝向
// 创建渲染器
const renderer = new THREE.WebGLRenderer(); //创建渲染器
renderer.setSize(w, h);// 向渲染器传递宽高
renderer.render(scene, camera);// 向渲染器传递场景和相机
document.body.append(renderer.domElement);
</script>
</body>
</html>
3.物体的变换属性
(1)为了直观看到物体的变换,可以先创建一个坐标轴
const axes = new THREE.AxesHelper(2, 2, 2); // 创建坐标轴
scene.add(axes);
(2)位置变换
cube.position.x = -1;
cube.position.y = -1;
cube.position.z = -1;
cube.position.set(1, 1, 1); // 全写
(3)旋转变换
cube.rotation.x = 45 / 180 * Math.PI; // x轴旋转45度
cube.rotation.y = 45 / 180 * Math.PI; // y轴旋转45度
cube.rotation.z = 45 / 180 * Math.PI; // z轴旋转45度
(4)缩放变换
cube.scale.x = 2;
cube.scale.y = 2;
cube.scale.z = 2;
cube.scale.set = (2, 2, 2); // 整体放大2倍
4.动画函数
利用three自带的Clock()方法新建一个对象
调用该对象的getElapsedTime()方法,可以获得一个和秒相同时间的递增
const clock = new THREE.Clock();
tick()
function tick() {
const time = clock.getElapsedTime()
cube.rotation.z = time;
cube.position.x = Math.sin(time * 2) * 2;
cube.position.y = Math.cos(time * 2) * 2;
requestAnimationFrame(tick);
renderer.render(scene, camera);
}