THREE.js----01
概述
three.js是JavaScript编写的WebGL第三方库,是对WebGL的封装,提供了非常多的3D显示功能,因为完全使用WebGL来实现3D效果还是挺麻烦的,开发效率不高。
Three.js 是一款运行在浏览器中的 3D 引擎,你可以用它创建各种三维场景,包括了摄影机、光影、材质等各种对象。你可以在它的主页上看到许多精采的演示。
基础
官网
版本下载地址
创建场景
为了让 three.js 展现物品,我们需要三个重要的组成部分:场景、相机以及渲染器,这样我们就能保证透过相机渲染出场景。
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement);
- 这里使用的是PerspectiveCamera 相机
- 第一个参数是视野角度,也就是能在显示器上看到的场景范围,单位是角度
- 第二个参数是长宽比
- 第三个参数是近截面
- 第四个参数是远截面
- 注:物体若不在远近截面之间则不会在场景中显示
创建立方体
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0xff00ff });
const cube = new THREE.Mesh(geometry, material); scene.add(cube);
- 几何体:创建一个立方体,使用BoxGemomety(几何体),这个对象包含了立方体所有的顶点和面
- 材质:是给我们得立方体添加颜色,使用MeshBasicMaterial,颜色设置为 0xff00ff
- 网格:用网格包含几何体上的材质,并将网格对象放入到我们得场景中
渲染场景
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
动起来
在此之前我们会看到一个立方体,接下来我们让他动起来
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
整体代码
<html>
<head>
<meta charset="utf-8" />
<title>three</title>
<style>
canvas {
width: 100%;
height: 100%;
}
</style>
<script src="./js/three.js"></script>
</head>
<body>
<script>
// 创建一个场景
const scene = new THREE.Scene();
// 创建一个相机,透视相机
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
// 渲染器
const renderer = new THREE.WebGLRenderer({
antialias: true, // 抗锯齿
});
// 设置渲染器的大小为窗口的内宽度,也就是内容区的宽度
renderer.setSize(window.innerWidth, window.innerHeight);
// 设置之后界面不容易模糊
renderer.setPixelRatio(window.devicePixelRatio);
// 添加到 body 上
document.body.appendChild(renderer.domElement);
// 创建一个立体矩形
const geometry = new THREE.BoxGeometry(1, 1, 1);
// 创建材质
const material = new THREE.MeshBasicMaterial({
color: 0xff00ff,
});
// 创建 cube
const cube = new THREE.Mesh(geometry, material);
// 添加到场景中
scene.add(cube);
camera.position.z = 5;
// 循环渲染
function render() {
requestAnimationFrame(render);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
render();
</script>
</body>
</html>