Create a rotating cube with Three.js

Create a rotating cube with Three.js

In this tech blog, we'll walk through how to use Three.js to create a simple scene consisting of a rotating cube. We will learn how to set up the scene, camera, cube and renderer, and how to use OrbitControls and the gsap library to animate and interact with the rotation of the cube.

Preparation

Before we start, we need to make sure the following preparations are done:

  1. Create an HTML file in your project directory, for example index.html, and include the Three.js library and the OrbitControls library in it:
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Three.js Rotate Cube</title>
    </head>
    <body>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/jsm/controls/OrbitControls.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.8.0/gsap.min.js"></script>
      <script src="app.js"></script>
    </body>
    </html>
    

  2. Create a file in your project directory app.jsand copy the Three.js code you provided into it.
  3. Create the scene and cube

    Here is the code to create the scene, camera, cube and renderer in Three.js:

    // 导入Three.js库中的所有模块,并命名为THREE
    import * as THREE from 'three';
    // 导入OrbitControls模块,并命名为OrbitControls
    import { OrbitControls} from "three/examples/jsm/controls/OrbitControls";
    // 导入gsap库,并命名为gsap
    import { gsap } from "gsap";
    
    // 创建一个Three.js场景
    const scene = new THREE.Scene();
    
    // 创建透视相机,参数分别为视野角度,长宽比,近裁剪面和远裁剪面
    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    // 设置相机位置
    camera.position.set(10, 10, 10);
    // 将相机添加到场景中
    scene.add(camera);
    
    // 创建立方体的几何体
    const box = new THREE.BoxGeometry(1, 1, 1);
    // 创建立方体的材质,颜色为绿色
    const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
    // 创建立方体,并将几何体和材质传入
    const cube = new THREE.Mesh(box, material);
    // 将立方体添加到场景中
    scene.add(cube);
    
    // 创建WebGL渲染器
    const renderer = new THREE.WebGLRenderer();
    // 设置渲染器的大小为窗口大小
    renderer.setSize(window.innerWidth, window.innerHeight);
    // 将渲染器的DOM元素添加到页面中
    document.body.appendChild(renderer.domElement);

 

The above code creates a Three.js scene and adds a green cube to the scene. The camera's position is set to (10, 10, 10) so that we can see the cube from different angles.

Add OrbitControls

To be able to control the camera view with the mouse, we use the OrbitControls library:

// 使用OrbitControls添加交互控制
const controls = new OrbitControls(camera, renderer.domElement);
// 启用阻尼效果,使控制更加平滑
controls.enableDamping = true;

With this code, we added OrbitControls that allow the user to rotate and scale the contents of the scene by dragging and scrolling with the mouse.

Rendering and Animation

// 定义渲染和动画函数
function render(time) {
  // 更新OrbitControls的状态,以响应用户的交互
  controls.update();
  // 渲染场景和相机
  renderer.render(scene, camera);
  // 使用requestAnimationFrame持续进行渲染和动画
  requestAnimationFrame(render);
}

// 调用渲染和动画函数,启动动画效果
render();

The above code is a rendering function, which is used requestAnimationFrameto continuously update the scene and camera to achieve animation effects. controls.update()Used to update the state of OrbitControls so that the user can interactively control the rotation of the scene.

Use gsap to create animation effects

const gs = gsap.to(cube.rotation, {
  // 动画持续时间为5秒
  duration: 5,
  // 绕y轴旋转360度,即一圈
  y: Math.PI * 2,
  // 动画重复次数为无限次
  repeat: -1,
  // 动画来回反复播放
  yoyo: true,
  // 延迟1秒后开始动画
  delay: 1,
  // 使用反弹效果的缓动函数
  ease: "bounce.out"
});

In this code, we use the gsap library to create a cube rotation animation. The rotation of the cube is around the y-axis, and has a bounce effect, which lasts 5 seconds and repeats continuously.

Add interactivity

// 添加双击事件监听器,用于暂停或继续动画
window.addEventListener("dblclick", () => {
  // 如果动画正在进行中,则暂停动画
  if (gs.isActive()) {
    gs.pause();
  } else {
    // 如果动画已经暂停,则继续动画
    gs.resume();
  }
});
//可以自己调整为双击进入全屏
  const fullscreen=document.fullscreenElement||document.webkitFullscreenElement;
  if(!fullscreen){
    renderer.domElement.requestFullscreen();
  }
  else{
    document.exitFullscreen();
  }

 The above code adds a double-click event listener to the window. When the user double-clicks the window, we check to see if the cube's rotation animation is in progress, and if so, pause the animation; if not, continue the animation.

Responding to window size changes

// 添加窗口大小改变事件监听器,使场景自适应窗口大小
window.addEventListener("resize", () => {
  // 更新相机的长宽比
  camera.aspect = window.innerWidth / window.innerHeight;
  // 更新相机投影矩阵
  camera.updateProjectionMatrix();
  // 更新渲染器的大小
  renderer.setSize(window.innerWidth, window.innerHeight);
  // 重新渲染场景和相机
  renderer.render(scene, camera);
});

Finally, we add an event listener for window resizing. When the user resizes the window, we resize the camera's perspective and the renderer's size to maintain the aspect ratio of the scene.

run the application

With the above code, we have successfully created a Three.js scene, which contains a rotating cube. The user can control the rotation and scaling of the scene with the mouse, and double-click the window to pause and continue the rotation animation of the cube. At the same time, when the user resizes the window, the scene will automatically adapt to the window size.

 

 

 

Guess you like

Origin blog.csdn.net/weixin_60895836/article/details/132046735