| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- <template>
- <div>
- <h2>3D 预览</h2>
- <div ref="threeCanvas" style="width: 400px; height: 400px;"></div>
- </div>
- </template>
- <script setup>
- import { onMounted, ref } from 'vue'
- import * as THREE from 'three'
- import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
- const threeCanvas = ref(null)
- let scene, camera, renderer, controls
- onMounted(() => {
- initScene()
- createTexturedBox()
- animate()
- })
- const initScene = () => {
- scene = new THREE.Scene()
- scene.background = null // 背景透明
- camera = new THREE.PerspectiveCamera(75, 1, 0.1, 1000)
- camera.position.set(0, 0, 5)
- renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true })
- renderer.setSize(400, 400)
- threeCanvas.value.appendChild(renderer.domElement)
- controls = new OrbitControls(camera, renderer.domElement)
- controls.enableDamping = true
- // 添加环境光
- const ambientLight = new THREE.AmbientLight(0xffffff, 1.0)
- scene.add(ambientLight)
- // 添加方向光
- const directionalLight = new THREE.DirectionalLight(0xffffff, 1.0)
- directionalLight.position.set(5, 5, 5)
- scene.add(directionalLight)
- }
- const createTexturedBox = () => {
- const geometry = new THREE.BoxGeometry(2.2, 3.5, 0.8)
- const textureLoader = new THREE.TextureLoader()
- // 确保纹理加载完成后再使用
- textureLoader.load(
- '/src/assets/zh.jpg',
- (texture) => {
- const material = new THREE.MeshStandardMaterial({ map: texture })
- const materials = new Array(6).fill(material)
- const box = new THREE.Mesh(geometry, materials)
- scene.add(box)
- },
- undefined,
- (error) => {
- console.error('纹理加载失败:', error)
- }
- )
- }
- const animate = () => {
- requestAnimationFrame(animate)
- controls.update()
- renderer.render(scene, camera)
- }
- </script>
- <style scoped>
- h2 {
- font-size: 18px;
- margin-bottom: 10px;
- }
- </style>
|