home Cloud computing and code文章正文

html5旋轉代碼,Three.js 旋轉水杯的代碼

Cloud computing and code 2023年05月24日 23:26 642 warenet

以下是一個簡單的html5旋轉代碼,引入Three.js 旋轉水杯的代碼,用html代碼演示效果如下:

 

html5旋轉代碼,Three.js 旋轉水杯的代碼 第1张

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Three.js 旋轉水杯</title>
    <style>
      body {
        margin: 0;
        overflow: hidden;
      }
    </style>
  </head>
  <body>
    <script src="https://dm.qunapu.com/threejs/build/three.min.js"></script>
    <script>
      var camera, scene, renderer;
      var cup;
      init();
      animate();
      function init() {
        // 創建場景對象
        scene = new THREE.Scene();
        // 創建相機對象
        camera = new THREE.PerspectiveCamera(
          45,
          window.innerWidth / window.innerHeight,
          1,
          1000
        );
        camera.position.set(0, 0, 10);
        // 創建渲染器
        renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setPixelRatio(window.devicePixelRatio);
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(renderer.domElement);
        // 創建幾何體
        var geometry = new THREE.CylinderGeometry(2, 2, 4, 20, 1, false);
        var material = new THREE.MeshNormalMaterial();
        cup = new THREE.Mesh(geometry, material);
        scene.add(cup);
      }
      function animate() {
        // 循環動畫
        requestAnimationFrame(animate);
        // 旋轉水杯
        cup.rotation.x += 0.01;
        cup.rotation.y += 0.01;
        // 渲染場景和相機
        renderer.render(scene, camera);
      }
    </script>
  </body>
</html>

 

- `window.innerWidth` 和 `window.innerHeight`:用於設置相機視錐體的寬度和高度。

- `camera.position.set(0, 0, 10);`:設置相機位置。

- `renderer.setPixelRatio(window.devicePixelRatio);`:設置渲染器的設備像素比。

- `var geometry = new THREE.CylinderGeometry(2, 2, 4, 20, 1, false);`:創建一個圓柱幾何體對象,前兩個參數分別設置上下底面的半徑,第三個參數設置高度,第四個參數設置圓柱面的分段數,第五個參數設Pinned post 部是否封口,第六個參數設置是否朝上。

- `var material = new THREE.MeshNormalMaterial();`:創建材質對象,使用 MeshNormalMaterial 材質。

- `cup = new THREE.Mesh(geometry, material);`:創建網格對象,將幾何體和材質傳遞給它。

- `cup.rotation.x += 0.01; cup.rotation.y += 0.01;`:每幀改變水杯的旋轉角度。

效果圖截圖:

標籤: html5旋轉代碼

AmupuCopyright Amupu.Z-Blog.Some Rights Reserved.