ThreeJs

11/3/2020 threejs
html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r122/three.min.js"></script>
  <style>
    html,
    body,
    .three-box {
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
    }

    .three-box {
      background-color: #eee;
    }
  </style>
</head>

<body>
  <div class="three-box" id='box'></div>
</body>
<script src="./index.js"></script>

</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
js
// 参数为挂载3d容器的dom
function init(el) {
  // 获取容器宽高
  const { offsetWidth, offsetHeight } = el
  // 实例化一个场景
  var scene = new THREE.Scene();
  // 实例化一个透视相机   参数  视野角度 长宽比 近截面 远截面 
  var camera = new THREE.PerspectiveCamera(75, offsetWidth / offsetHeight, 0.1, 1000);
  // 实例化一个渲染器
  var renderer = new THREE.WebGLRenderer();
  // 设置渲染器尺寸  参数 宽  高   updateStyle
  renderer.setSize(offsetWidth, offsetHeight);

  // 下面几行代码是初始化一个立方体,设定了材质 形状
  const geometry = new THREE.BoxGeometry();
  const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
  const cube = new THREE.Mesh(geometry, material);

  // 将立方体加入场景
  scene.add(cube);
  // 设置相机的位置
  camera.position.z = 5;
  // 挂载渲染器
  el.appendChild(renderer.domElement);

  // 启动一个动画
  let frame = null
  function animate() {
    frame = requestAnimationFrame(animate);
    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;
    renderer.render(scene, camera);
  }
  animate();
  // 返回一个清除函数
  return () => frame && cancelAnimationFrame(frame)

}


init(document.getElementById('box'))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
Last Updated: 12/3/2020, 2:41:32 PM