关于前端:用Threejs做一个地球自转月球绕着地球转的Demo

6次阅读

共计 1810 个字符,预计需要花费 5 分钟才能阅读完成。

Third Scene

实现一个月球绕着地球旋转的 Demo

源码地址 threejs-demo

预览地址

须要用到的包

<!-- three.js 包 -->
<script src="./three.js"></script>
<script src="./OrbitControls.js"></script>
<script src="./CSS2DRenderer.js"></script>

实现

  1. 创立 scence,实例化纹理加载器,增加时钟
const clock = new THREE.Clock();
// 实例化纹理加载器
const textureLoader = new THREE.TextureLoader();
const scene = new THREE.Scene();
  1. 创立地球对象和月球对象
  • 实例化月球对象
const moonGeometry = new THREE.SphereGeometry(5, 30, 30);
const moonMaterial = new THREE.MeshPhongMaterial({map: textureLoader.load("./imgs/moon.jpg"),
});
const moon = new THREE.Mesh(moonGeometry, moonMaterial);
scene.add(moon);
  • 实例化地球对象

    • shininess 高亮的水平,越高的值越闪亮
    • map 色彩贴图
const earthGeometry = new THREE.SphereGeometry(50, 50, 50);
const earthMaterial = new THREE.MeshPhongMaterial({
  shininess: 5,
  map: textureLoader.load(`./imgs/worldmap.jpg`),
});
const earth = new THREE.Mesh(earthGeometry, earthMaterial);
scene.add(earth);
  1. 动画
function animation() {const elapsed = clock.getElapsedTime();
  moon.position.set(Math.sin(elapsed) * 100, 0, Math.cos(elapsed) * 100);
  const axis = new THREE.Vector3(0, 1, 0);
  earth.rotateOnAxis(axis, (elapsed * Math.PI) / 1000);
  renderer.render(scene, camera);
  requestAnimationFrame(animation);
}
animation();

切换地图

顺便尝试一下尤大新出的 petite-vue,petite-vue 在 html 中应用就非常不便了,又轻又小,一键应用

<div id="app" v-scope @vue:mounted="mounted">
  <div class="select-container">
    <span> 切换地图 </span>
    <select v-model="index" @change="change">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
      <option value="5">5</option>
      <option value="6">6</option>
    </select>
  </div>
  <div class="loading-container" v-if="!domElement">Loading...</div>
</div>
import {createApp} from "https://unpkg.com/petite-vue?module";

createApp({
  index: 1,
  domElement: null,
  mounted() {this.domElement = init(this.index);
  },
  change(event) {app.removeChild(this.domElement);
    this.domElement = null;
    setTimeout(() => {this.domElement = init(this.index);
    }, 500);
  },
}).mount();

最终实现成果

正文完
 0