Vue3炫酷可旋转的3D地球

首先,我们需要安装Three.js库:

npm install three

接下来,我们创建一个Vue3项目,并在项目中引入Three.js库。在src/main.js文件中,编写以下代码:

import { createApp } from 'vue'
import App from './App.vue'
import * as THREE from 'three'

const app = createApp(App)

app.config.globalProperties.$three = {
  init: () => {
    // 创建场景
    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()
    renderer.setSize(window.innerWidth, window.innerHeight)
    document.body.appendChild(renderer.domElement)

    // 创建地球
    const geometry = new THREE.SphereGeometry(1, 32, 32)
    const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 })
    const earth = new THREE.Mesh(geometry, material)
    scene.add(earth)

    // 渲染循环
    const animate = () => {
      requestAnimationFrame(animate)

      // 旋转地球
      earth.rotation.y += 0.01

      renderer.render(scene, camera)
    }

    animate()
  }
}

app.mount('#app')

src/App.vue文件中,编写以下代码:

<template>
  <div id="app">
    <canvas ref="earthCanvas">canvas>
  div>
template>

<script>
export default {
  mounted() {
    this.$refs.earthCanvas.getContext('webgl').call(this.$three.init(), this)
  }
}
script>

现在,运行项目,你将看到一个可旋转的3D地球。你可以根据需要修改地球的颜色、大小等属性。

你可能感兴趣的:(Vue3,3d,vue.js,前端,javascript)