一个vue页面显示一个地球的代码
时间: 2024-05-06 18:20:22 浏览: 10
以下是一个基于Three.js的vue页面,用于显示一个地球:
```html
<template>
<div ref="container"></div>
</template>
<script>
import * as THREE from 'three'
export default {
name: 'Earth',
mounted () {
// 创建场景
const scene = new THREE.Scene()
// 创建相机
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
)
camera.position.z = 5
// 创建渲染器
const renderer = new THREE.WebGLRenderer({ antialias: true })
renderer.setSize(window.innerWidth, window.innerHeight)
this.$refs.container.appendChild(renderer.domElement)
// 加载地球贴图
const loader = new THREE.TextureLoader()
const earthTexture = loader.load(require('@/assets/earth.jpg'))
// 创建地球
const earthGeometry = new THREE.SphereGeometry(2, 32, 32)
const earthMaterial = new THREE.MeshBasicMaterial({ map: earthTexture })
const earth = new THREE.Mesh(earthGeometry, earthMaterial)
scene.add(earth)
// 渲染循环
const animate = function () {
requestAnimationFrame(animate)
earth.rotation.y += 0.005
renderer.render(scene, camera)
}
animate()
}
}
</script>
<style>
canvas {
width: 100%;
height: 100%;
}
</style>
```
需要注意的是,此代码需要引入Three.js和一个地球的贴图(此处使用了`earth.jpg`)。在`mounted`钩子函数中,首先创建了场景、相机和渲染器,并将渲染器的canvas元素添加到组件的容器中。然后使用`TextureLoader`加载地球贴图,并创建一个`SphereGeometry`和一个`MeshBasicMaterial`,将它们合并成一个`Mesh`并添加到场景中。最后启动渲染循环,不断更新地球的旋转角度并渲染场景。