這裡我用的是vue框架:
首先下載安裝three.js => npm install three;然後import * as THREE from 'three'匯入元件中;接下來就可以在元件中編寫我們的three.js程式碼
- 建立場景:
const scene = new THREE.Scene()
- 建立相機:
const camera = new THREE.PerspectiveCamera(70, //視角度數window.innerWidth / window.innerHeight, //寬高比0.1, //近平面1000 //遠平面)//設定相機位置camera.position.z=-1
-
建立渲染器及繫結渲染節點:const renderer = new THREE.WebGLRenderer();renderer.setSize(window.innerWidth,window.innerHeight)document.body.appendChild(renderer.domElement);
-
建立幾何體(我這邊建立的是正方體):const zhengfangxing = new THREE.BoxGeometry(10,10,10);
-
建立軌道控制器以及設定阻尼const controls = new OrbitControls(camera,renderer.domElement)//設定帶有阻尼的慣性controls.enableDamping = true//設定阻尼的係數(阻尼越大,滑動越慢)controls.dampingFactor = 0.5
-
貼圖(蔣正方體的六個面貼上對應的圖片)//匯入照片var arr = ['zuo','you','shang','xia','qian','hou']var tietu = []//載入圖片arr.forEach((item)=>{//紋理載入let img = new THREE.TextureLoader().load(`/src/assets/keting/${item}.jpg`,function(){renderer.render(scene,camera)})console.log(img,'-------------------------')//建立材質貼圖(new THREE.MeshBasicMaterial ==》設定正方體的材質)tietu.push(new THREE.MeshBasicMaterial({ map: img }))})
-
建立網格://將正方體和材質放入網格const cube = new THREE.Mesh(zhengfangxing,tietu)然後將網格新增到場景中scene.add(cube)最後定義animate函式渲染和更新function animate(){//請求每一幀函式requestAnimationFrame(animate)//渲染renderer.render(scene,camera)controls.update()}animate()註釋:如果大小效果不合適可以透過集合體的scale()方法縮放大小