Three.js 简约的3D房间

文化   2024-10-25 09:49   河南  

使用 Three.js 的 WebGL 小实验。简约的3D房间。

实现代码

HTML:

<canvas class="webgl"></canvas>

<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r124/three.min.js"></script><script src="https://unpkg.com/three@0.126.0/examples/js/loaders/GLTFLoader.js"></script><script src="https://unpkg.com/three@0.126.0/examples/js/controls/OrbitControls.js"></script>
CSS:
*,*::after,*::before {margin: 0;padding: 0;box-sizing: border-box;    outline: none;}

body{ overflow: hidden; background-color: #949494;cursor: grab;}

.webgl{ position: fixed; top: 0; left: 0;}

JAVASCRIPT:

const canvas = document.querySelector('.webgl')const scene = new THREE.Scene()const textureLoader = new THREE.TextureLoader()const sizes = {    width: window.innerWidth,    height: window.innerHeight}

// Base cameraconst camera = new THREE.PerspectiveCamera(10, sizes.width / sizes.height, 0.1, 100)camera.position.x = 18camera.position.y = 8camera.position.z = 20scene.add(camera)

//Controlsconst controls = new THREE.OrbitControls(camera, canvas)controls.enableDamping = truecontrols.enableZoom = truecontrols.enablePan = falsecontrols.minDistance = 20controls.maxDistance = 40controls.minPolarAngle = Math.PI / 4controls.maxPolarAngle = Math.PI / 2controls.minAzimuthAngle = - Math.PI / 80controls.maxAzimuthAngle = Math.PI / 2.5

// Rendererconst renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true, alpha: true})

renderer.setSize(sizes.width, sizes.height)renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))renderer.outputEncoding = THREE.sRGBEncoding

// Materialsconst bakedTexture = textureLoader.load('https://rawcdn.githack.com/ricardoolivaalonso/ThreeJS-Room05/ae27bdffd31dcc5cd5a919263f8f1c6874e05400/baked.jpg')bakedTexture.flipY = falsebakedTexture.encoding = THREE.sRGBEncoding

const bakedMaterial = new THREE.MeshBasicMaterial({ map: bakedTexture, side: THREE.DoubleSide,})

//Loaderconst loader = new THREE.GLTFLoader()loader.load('https://rawcdn.githack.com/ricardoolivaalonso/ThreeJS-Room05/ae27bdffd31dcc5cd5a919263f8f1c6874e05400/model.glb', (gltf) => { const model = gltf.scene model.traverse( child => child.material = bakedMaterial ) scene.add(model) }, ( xhr ) => {console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' ) })



window.addEventListener('resize', () =>{ sizes.width = window.innerWidth sizes.height = window.innerHeight camera.aspect = sizes.width / sizes.height camera.updateProjectionMatrix() renderer.setSize(sizes.width, sizes.height) renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))})// Animationconst tick = () => { controls.update() renderer.render(scene, camera) window.requestAnimationFrame(tick)}

tick()


源码:

https://codepen.io/ricardoolivaalonso/pen/KKbWGNZ


体验:

https://codepen.io/ricardoolivaalonso/full/KKbWGNZ




感谢您的阅读      

在看点赞 好文不断  

初识Threejs
初识 Three.js 的奇妙世界,走进三维空间,与小编一起拥抱前端技术,涉及WebGL、WebGPU、Threejs、Shader、GIS、VR/AR、数字孪生、3D图形学等。
 最新文章