“使用 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>
*,
*::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 camera
const camera = new THREE.PerspectiveCamera(10, sizes.width / sizes.height, 0.1, 100)
camera.position.x = 18
camera.position.y = 8
camera.position.z = 20
scene.add(camera)
//Controls
const controls = new THREE.OrbitControls(camera, canvas)
controls.enableDamping = true
controls.enableZoom = true
controls.enablePan = false
controls.minDistance = 20
controls.maxDistance = 40
controls.minPolarAngle = Math.PI / 4
controls.maxPolarAngle = Math.PI / 2
controls.minAzimuthAngle = - Math.PI / 80
controls.maxAzimuthAngle = Math.PI / 2.5
// Renderer
const 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
// Materials
const bakedTexture = textureLoader.load('https://rawcdn.githack.com/ricardoolivaalonso/ThreeJS-Room05/ae27bdffd31dcc5cd5a919263f8f1c6874e05400/baked.jpg')
bakedTexture.flipY = false
bakedTexture.encoding = THREE.sRGBEncoding
const bakedMaterial = new THREE.MeshBasicMaterial({
map: bakedTexture,
side: THREE.DoubleSide,
})
//Loader
const 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))
})
// Animation
const tick = () => {
controls.update()
renderer.render(scene, camera)
window.requestAnimationFrame(tick)
}
tick()
源码:
https://codepen.io/ricardoolivaalonso/pen/KKbWGNZ
体验:
https://codepen.io/ricardoolivaalonso/full/KKbWGNZ