SemiFinishedRework.vue 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <template>
  2. <div>
  3. <h2>3D 预览</h2>
  4. <div ref="threeCanvas" style="width: 400px; height: 400px;"></div>
  5. </div>
  6. </template>
  7. <script setup>
  8. import { onMounted, ref } from 'vue'
  9. import * as THREE from 'three'
  10. import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
  11. const threeCanvas = ref(null)
  12. let scene, camera, renderer, controls
  13. onMounted(() => {
  14. initScene()
  15. createTexturedBox()
  16. animate()
  17. })
  18. const initScene = () => {
  19. scene = new THREE.Scene()
  20. scene.background = null // 背景透明
  21. camera = new THREE.PerspectiveCamera(75, 1, 0.1, 1000)
  22. camera.position.set(0, 0, 5)
  23. renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true })
  24. renderer.setSize(400, 400)
  25. threeCanvas.value.appendChild(renderer.domElement)
  26. controls = new OrbitControls(camera, renderer.domElement)
  27. controls.enableDamping = true
  28. // 添加环境光
  29. const ambientLight = new THREE.AmbientLight(0xffffff, 1.0)
  30. scene.add(ambientLight)
  31. // 添加方向光
  32. const directionalLight = new THREE.DirectionalLight(0xffffff, 1.0)
  33. directionalLight.position.set(5, 5, 5)
  34. scene.add(directionalLight)
  35. }
  36. const createTexturedBox = () => {
  37. const geometry = new THREE.BoxGeometry(2.2, 3.5, 0.8)
  38. const textureLoader = new THREE.TextureLoader()
  39. // 确保纹理加载完成后再使用
  40. textureLoader.load(
  41. '/src/assets/zh.jpg',
  42. (texture) => {
  43. const material = new THREE.MeshStandardMaterial({ map: texture })
  44. const materials = new Array(6).fill(material)
  45. const box = new THREE.Mesh(geometry, materials)
  46. scene.add(box)
  47. },
  48. undefined,
  49. (error) => {
  50. console.error('纹理加载失败:', error)
  51. }
  52. )
  53. }
  54. const animate = () => {
  55. requestAnimationFrame(animate)
  56. controls.update()
  57. renderer.render(scene, camera)
  58. }
  59. </script>
  60. <style scoped>
  61. h2 {
  62. font-size: 18px;
  63. margin-bottom: 10px;
  64. }
  65. </style>