#1 初步使用ThreeJS
2018-08-01 本文已影响12人
JamesSawyer
/**
* 三要素
* 场景 scene
* 相机 camra
* 渲染器 renderer
*/
const scene = new THREE.Scene();
// Perspective 透视
/**
* 透视相机
* @param 75 表示FOV(field of view) 视角角度,单位 degrees
* @param window.innerWidth / window.innerHeight 表示aspect ratio 宽高比/横纵比
* @param 0.1 表示近平面距离 表示距离相机小于0.1的物件将不会被放进场景中 这些值对性能优化时会有用
* @param 1000 表示远平面距离 表示距离相机大于1000的物件将不会被放进场景中
*/
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
/**
* 渲染器
* 除了WebGLRenderer外 还有
* CSS2DRenderer && CSS3DRenderer && SVGRenderer && CanvasRenderer
*/
const renderer = new THREE.WebGLRenderer();
/**
* 设置渲染器渲染的大小
* 还可以使用 renderer.setSize(window.innerWidth / 2, window.innerHeight / 2, false) 表示降低分辨率来适配画布
*/
renderer.setSize(window.innerWidth, window.innerHeight);
// 将渲染器元素添加到HTML文档中
// renderer.domElement 这是一个canvas元素
document.body.appendChild(renderer.domElement);
// BoxGeometry 是包含了所有顶点数据和面的立方体
const geometry = new THREE.BoxGeometry(1, 1, 1);
// 添加材质和颜色 (此处 0x00ff00 是绿色)
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
// Mesh 可以将材质添加到geometry(几何体)上
const cube = new THREE.Mesh(geometry, material);
scene.add(cube); // 默认会添加到场景 (0,0,0) 位置,导致相机和物件重合
camera.position.z = 5;
// 上面代码只是将场景,相机,物件进行了声明,实际上并没有开始渲染任何东西
function animate() {
// requestAnimationFrame 当用户导航到其它浏览器tab时,刷新操作会暂停 避免浪费进程资源和电池
// 60FPS
requestAnimationFrame(animate);
// 添加旋转
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
其它:
# index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="index.css">
<title>Document</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/95/three.min.js"></script>
<script src="index.js"></script>
</body>
</html>
# index.css
body {
margin: 0;
}
canvas {
width: 100%;
height: 100%;
}