【ThreeJs】the first demo —— Dancing BoxGeometry

这篇博客介绍了如何使用three.js库创建一个3D立方体,并实现立方体的旋转动画。首先引入three.js库,然后创建场景、透视相机和WebGL渲染器。接着,通过BoxGeometry和MeshBasicMaterial创建立方体,将其添加到场景中,并设置相机位置。最后,使用requestAnimationFrame实现动画循环,不断更新立方体的旋转角度,实现平滑的3D旋转效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上代码
three.js 源码 copy https://threejs.org/build/three.js

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>My first three.js app</title>
    <style>
      body {
        margin: 0;
      }
    </style>
  </head>
  <body>
    <script src="../public/three.js"></script>
    <script>
      // 参考 https://threejs.org/docs/index.html#manual/zh/introduction/Creating-a-scene
      // Our Javascript will go here.
      const scene = new THREE.Scene()
      // PerspectiveCamera 透视摄像机
      // 参数:视野角度(FOV),长宽比(aspect ratio),近截面(near)和远截面(far)只能看到两个值之间的物体
      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)

      // 添加一个立方体
      const geometry = new THREE.BoxGeometry(1, 1, 1) // 立方体,可设置 顶点(vertices)和面(faces)
      const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }) // 材质
      const cube = new THREE.Mesh(geometry, material) // Mesh(网格)
      scene.add(cube) // 被添加到(0,0,0)坐标,摄像机和物体重合

      camera.position.z = 5 // 相机向外移点

      // 需要 “渲染循环”(render loop)或者“动画循环”(animate loop)
      // 屏幕刷新率一般是60次/秒,因此 创建了一个使渲染器 能够在每次屏幕刷新时 对场景进行绘制的循环
      // why not setInterval? 因为 requestAnimationFrame 当用户切换到其它的标签页时,它会暂停,因此不会浪费用户宝贵的处理器资源,也不会损耗电池的使用寿命。
      function animate() {
        requestAnimationFrame(animate)
        // let's dance!
        cube.rotation.x += 0.01
        cube.rotation.y += 0.01
        renderer.render(scene, camera)
      }
      animate()
    </script>
  </body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值