自学内容网 自学内容网

3D地球小demo

文章说明

简单了解three.js,书写一个3D地球的效果,目前的效果很粗糙,等待后续继续完善

核心代码

需要先安装依赖

npm install three

App.vue

<script setup>
import {onMounted, onUnmounted, ref} from 'vue';
import * as THREE from 'three';
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls';

const earthContainer = ref();

onMounted(() => {
  init();
  animate();
});

onUnmounted(() => {
  dispose();
});

let scene, camera, renderer, controls;

function init() {
  // 场景
  scene = new THREE.Scene();

  // 相机
  const width = earthContainer.value.clientWidth;
  const height = earthContainer.value.clientHeight;
  camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
  camera.position.z = 2;

  // 渲染器
  renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.setSize(width, height);
  renderer.setPixelRatio(window.devicePixelRatio); // 高清显示
  earthContainer.value.appendChild(renderer.domElement);

  // 加载纹理
  const textureLoader = new THREE.TextureLoader();
  const earthTexture = textureLoader.load('earth.jpg');

  // 设置星空背景
   // 替换为你的星空图片路径
  scene.background = textureLoader.load('stars.jpg'); // 将星空纹理设置为场景的背景

  // 地球材质和几何体
  const geometry = new THREE.SphereGeometry(0.5, 32, 32);
  const material = new THREE.MeshBasicMaterial({ map: earthTexture });
  const earth = new THREE.Mesh(geometry, material);
  scene.add(earth);

  // 控制
  controls = new OrbitControls(camera, renderer.domElement);

  // 灯光
  const ambientLight = new THREE.AmbientLight(0xffffff, 0.5); // soft white light
  scene.add(ambientLight);
}

function animate() {
  requestAnimationFrame(animate);
  controls.update(); // only required if controls.enableDamping = true, or if controls.autoRotate = true
  renderer.render(scene, camera);
}

function dispose() {
  controls.dispose();
  renderer.dispose();
  renderer.forceContextLoss();
  renderer.domElement.remove();
}
</script>

<template>
  <div ref="earthContainer" class="earth-container"></div>
</template>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.earth-container {
  width: 100vw;
  height: 100vh;
  position: relative; /* 确保容器能够正确包含渲染器 */
}
</style>

效果展示

默认效果在这里插入图片描述

放大
在这里插入图片描述

旋转
在这里插入图片描述

源码下载

3D地球demo


原文地址:https://blog.csdn.net/bingbingyihao/article/details/144370866

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!