threejs三大要素
场景 相机 渲染器
// 场景
const scene = new THREE.Scene();
scene.background = new THREE.Color("#cccccc")
scene.environment = "#cccccc"
// 相机
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 8, 45);
// 渲染器
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
开启灯光
// 灯光
// 前灯光
const light1 = new THREE.DirectionalLight(0xffffff, 1)
light1.position.set(0, 0, 10)
scene.add(light1)
// 后灯光
const light2 = new THREE.DirectionalLight(0xffffff, 1)
light2.position.set(0, 0, -10)
scene.add(light2)
// 左灯光
const light3 = new THREE.DirectionalLight(0xffffff, 1)
light3.position.set(-10, 0, 0)
scene.add(light3)
// 右灯光
const light4 = new THREE.DirectionalLight(0xffffff, 1)
light4.position.set(10, 0, 0)
scene.add(light4)
// 上灯光
const light5 = new THREE.DirectionalLight(0xffffff, 1)
light5.position.set(0, 10, 0)
scene.add(light5)
加载模型
const loader = new GLTFLoader()
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath("/draco/gltf/");
loader.setDRACOLoader(dracoLoader);
//后续可以加载各种模型
// 警车
let policeCars;
loader.load('/public/shoufeizhan/警车.glb', gltf => {policeCars = gltf.scene.children[0]scene.add(policeCars)
})
// 客车
let coachCar;
loader.load('/public/shoufeizhan/客车.glb', gltf => {coachCar = gltf.scenescene.add(coachCar)
})loader.load('/public/shoufeizhan/收费站.glb', gltf => {console.log(gltf);const model = gltf.scenemodel.traverse(child => {if (child.name.includes('通行杆')) {child.castShadow = truechild.receiveShadow = truechild.children.forEach(c => {c.isRotated = false})passagePoleList = child.children}
动画 Tweenjs
// 栏杆抬起放下的动画
function railingRotation(target) {return new Promise((res, rej) => {const targetRotation = { z: target.isRotated ? 0 : Math.PI / 2 };const rotationTween = new Tween(target.rotation).to(targetRotation, 1000).easing(TWEEN.Easing.Quadratic.InOut).start()tweens.push(rotationTween)rotationTween.onComplete(() => {target.isRotated = !target.isRotated})})
}