使用Three.js实现地球入场动画的示例代码

15 min read

以下是使用Three.js实现地球入场动画的示例代码:

<html>
<head>
    <meta charset="UTF-8">
    <title>Earth Intro Animation</title>
    <style>
        body {
            margin: 0;
            overflow: hidden;
        }
    </style>
</head>
<body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/TweenMax.min.js"></script>
    <script>
        // Create the scene and camera
        var scene = new THREE.Scene();
        var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        camera.position.set(0, 0, 20);

        // Create the renderer and add it to the DOM
        var renderer = new THREE.WebGLRenderer({ antialias: true });
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(renderer.domElement);

        // Add a light to the scene
        var light = new THREE.PointLight(0xffffff, 1, 100);
        light.position.set(0, 0, 10);
        scene.add(light);

        // Create the mesh for the earth
        var earthGeometry = new THREE.SphereGeometry(5, 50, 50);
        var earthMaterial = new THREE.MeshPhongMaterial({
            map: new THREE.TextureLoader().load('https://threejs.org/examples/textures/land_ocean_ice_cloud_2048.jpg'),
            bumpMap: new THREE.TextureLoader().load('https://threejs.org/examples/textures/land_ocean_ice_cloud_2048_bump.jpg'),
            bumpScale: 0.005,
            specularMap: new THREE.TextureLoader().load('https://threejs.org/examples/textures/water_2048.jpg'),
            specular: new THREE.Color('grey')
        });
        var earth = new THREE.Mesh(earthGeometry, earthMaterial);
        earth.rotation.y = -Math.PI / 2; // rotate the earth so that the lights are facing it
        scene.add(earth);

        // Set up the animation
        function animate() {
            requestAnimationFrame(animate);

            // Rotate the earth
            earth.rotation.y += 0.01;

            // Render the scene
            renderer.render(scene, camera);
        }

        // Start the animation
        animate();

        // Animate the camera position and zoom in on the earth
        TweenMax.to(camera.position, 5, { z: 5, ease: Power2.easeInOut });
        TweenMax.to(camera.position, 2, { y: 2, ease: Power2.easeInOut });
    </script>
</body>
</html>

首先,我们创建了一个Three.js场景和一个摄像机,并将其添加到HTML中。

然后,我们创建一个光源,并将其添加到场景中。

接下来,我们使用SphereGeometry构造函数创建一个球形几何形状,使用MeshPhongMaterial材质为球体添加纹理、凹凸贴图和镜面高光贴图。然后,我们将球体旋转-90度(即沿Y轴逆时针旋转pi/2),以使光照射到地球的面。

然后,我们设置了一个动画函数,在其中旋转地球并渲染场景。

最后,我们使用TweenMax库创建两个动画,将摄像机缓慢地缩放和移动到地球上方,以模拟地球入场动画。

注意:在本示例中,我们在CDN上加载Three.js和TweenMax库,所以在使用之前必须添加这些文件的引用。在实际项目中,您可以在本地使用这些库。