我在前端幹工地——three.js
highlight: a11y-dark
前段時間接觸了Three.js後,試著用他載入了一些模型three.js初體驗簡陋的瞭解了一下three.js的相關使用,並且寫下了第一篇文章。但是過後還是對很多一知半解,作為不會建模且目前沒有接觸到相關業務需求的開發,難道沒有模型就什麼都不會了嗎?因此我覺得有必要來試試沒有模型的情況下自己來構建場景,以便於加深理解。
我在前端幹工地,最後成果如下圖。預覽地址
從圖中可以看到,整個畫面由以下構成 1. 地面 2. 房子 3. 天空 下面就能一步步的構建這個場景。
一、 準備工作
我這裡的環境是vue3 + vite
,基本環境準備好後就要安裝three.js的庫,安裝完成後就可以繼續了。接下來搭建頁面的基本結構
```js
``
由於要將影象顯示到頁面中的
canvas中,因此需要在
onMounted生命週期內獲取,接下來建立一下構建場景的幾個要素:
相機(camera)、
場景(scene)、
渲染器(renderer)、
燈光(light),
在
onMounted`中新增如下程式碼:
```js canvas = document.querySelector("#draw"); //建立場景 scene = new THREE.Scene(); //建立一個透視相機 camera = new THREE.PerspectiveCamera(125, width / height, 1, 2000); //設定相機位置 camera.position.set(-30, 30, 50); //建立環境光 const hjLight = new THREE.AmbientLight(0xffffff); //新增環境光至場景 scene.add(hjLight);
//新增房子的group到場景中 scene.add(group); //新增軌道控制器 const controls = new OrbitControls(camera, canvas); //渲染器 renderer = new THREE.WebGLRenderer({ canvas,//傳入要渲染的canvas,相關引數可以看文件 antialias: true,//抗鋸齒 alpha: true, }); //設定渲染器大小 renderer.setSize(width, height);
//渲染器開始渲染 renderer.render(scene, camera); //執行 function animate() { controls.update(); renderer.render(scene, camera); } animate() ``` 通過以上程式碼,幾要素我們已經具有,下面可以正式開始了。
二、建立地面
地面這裡使用了three.js內建的CircleGeometry
幾何體,這裡沒有什麼強制需求,符合樣子就可以。
下面新增一個方法createGround
如下,隨便找一張圖片當作地面的材質,隨後呼叫,然後便可以看見一個半徑為500的圓形地面
```js //建立地面 function createGround() { //匯入材質 const groundTexture = new THREE.TextureLoader().load("/grass.webp"); groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping; groundTexture.repeat.set(100, 100); const ground = new THREE.CircleGeometry(500, 100); const groundMaterial = new THREE.MeshLambertMaterial({ side: THREE.DoubleSide, map: groundTexture, // transparent: true, // opacity: 0.2, });
const groundMesh = new THREE.Mesh(ground, groundMaterial); groundMesh.name = "地面";//設定name屬性 groundMesh.rotateX(-Math.PI / 2);//旋轉用於呈現一個水平的地面 scene.add(groundMesh); ``` 調整角度和大小後便能看到如下圖所示:
三、 開始建立房子
1、建立地板
在這裡建立地板,這裡使用的是內建的BoxGeometry
幾何體。新增createFloor
方法,如下:
```js //建立地板,可以理解為地基 function createFloor() { const texture = new THREE.TextureLoader().load("/img/wood.jpg"); //設定地板大小,由於後面將要生成牆體存在設定為1的厚度,因此這裡對地板的x,z均-2 const floor = new THREE.BoxGeometry(baseWidth - 2, 1, baseLength - 2); const material = new THREE.MeshPhongMaterial({ map: texture }); const mesh = new THREE.Mesh(floor, material); mesh.position.set(0, 1, 0); mesh.name = "地板"; group.add(mesh); }
``` 呼叫上面的方法後頁面中如下圖
2、建立左右兩邊的牆體
這裡開始左右兩邊的規則牆體,使用的也是內建的BoxGeometry
幾何體。新增 createWall
方法,這個方法返回建立的牆體
js
function createWall() {
const wallTexture = new THREE.TextureLoader().load("/img/wall1.jpg");
const wall = new THREE.BoxGeometry(baseLength, 20, 1);
const wallMaterial = new THREE.MeshPhongMaterial({
map: wallTexture,
});
//牆體的網格
const wallMesh = new THREE.Mesh(wall, wallMaterial);
return wallMesh;
}
接下來呼叫方法生成第一面牆
js
let leftWall = createWall()
leftWall.name = '左側的牆'
group.add(leftWall)
呼叫後畫面中應該如下圖
很顯然這與我們的預期不符,下面設定牆體的位置並且讓左側的牆旋轉90度,注意rotateY
的引數為弧度。
js
leftWall.rotateY(Math.PI / 2);
leftWall.position.set(-baseWidth / 2, 10, 0);
調整完成後如下圖
接下來我們如法炮製右側的牆,可以重新呼叫一次方法或者使用幾何體物件三的clone
方法。這裡使用clone
js
const rightWall = leftWall.clone();
rightWall.position.set(baseWidth / 2, 10, 0);
rightWall.name = "右側的牆";
group.add(rightWall);
調整後如下圖
3、建立前後的牆體
通過上圖可以看到房子前後的牆是不規則的,這個時候使用建立前面牆的幾何體便不行了,查閱文件後得知可以使用擠壓緩衝幾何體(ExtrudeGeometry)
,官網的描述如圖
如何使用呢,構造器
文件中清晰的表明了這個類有兩個引數,一個是 形狀或者包含形狀的陣列
和配置選項。那麼到這裡我產生了疑問,什麼是形狀的陣列呢,接著檢視文件找到了shape
這個類
例項程式碼中一眼望去熟悉的api映入眼簾,因此大概能想象出用法。
由於前後兩堵牆大致的形狀都是相同的,因此寫一個返回形狀陣列的方法
genwallShape
js
function genwallShape() {
const shape = new THREE.Shape();
let height = 20;//牆的高度
shape.moveTo(0, 0); //起點
shape.lineTo(0, height); //牆體高度
shape.lineTo(baseWidth / 2 - 1, height + 5); //牆體頂點
shape.lineTo(baseWidth / 2 - 1, height + 6); //牆體頂點
shape.lineTo(baseWidth / 2 + 1, height + 6); //牆體頂點
shape.lineTo(baseWidth / 2 + 1, height + 5); //牆體頂點
shape.lineTo(baseWidth, height);
shape.lineTo(baseWidth, 0);
shape.lineTo(0, 0);
return { shape };
}
生成點的陣列的的方法有了,接下來寫一個生成不規則牆體的方法createIrregularWall
js
//建立不規則牆體
function createIrregularWall(shape, position) {
const extrudeSettings = {
depth: 1,//定義深度,由於擠壓幾何體的點位都是x,y座標組成的二位平面,這個引數定義向z軸的延展長度,即為牆的厚度
bevelEnabled: false,
};
const wallTexture = new THREE.TextureLoader().load("/img/wall1.jpg");
const geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings);
wallTexture.wrapS = wallTexture.wrapT = THREE.RepeatWrapping;
wallTexture.repeat.set(0.05, 0.05);
const material = new THREE.MeshPhongMaterial({ map: wallTexture });
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(...position);
group.add(mesh);
return mesh;
}
點位有了、方法也有了,下面開始建立後牆,新增一個對應的方法
js
//建立不帶門的不規則牆體
function createNoDoorWall() {
let { shape } = genwallShape();
let mesh = createIrregularWall(shape, [-baseWidth / 2, 0, -baseLength / 2]);
mesh.name = "帶門的牆對面的牆";
}
呼叫後如圖
接下來建立帶門洞的方法,問題又來了,怎麼在牆上打洞呢,還是在文件中找到了答案
shape上有一個屬性表示了孔洞了,接下來就好辦了
js
function createDoorWall() {
let { shape } = genwallShape();
const door = new THREE.Path();
//門的位置
door.moveTo(baseWidth / 2 + 5, 0);
door.lineTo(baseWidth / 2 + 5, 16);
door.lineTo(baseWidth / 2 - 5, 16);
door.lineTo(baseWidth / 2 - 5, 0);
door.lineTo(baseWidth / 2 + 5, 0);
// 形狀上的孔洞
shape.holes.push(door);
let mesh = createIrregularWall(shape, [
-baseWidth / 2,
0,
baseLength / 2 - 1,
]);
mesh.name = "帶門的牆";
}
呼叫後如下
可以看到門的形狀已經出來了
4、建立屋頂
這裡我們開始建立屋頂,首先求出屋頂的寬度,也就是我們要建立的幾何體的z軸的延展
```js function createRoof() {
//屋頂寬 let width = Math.sqrt((baseWidth / 2) 2 + 5 2) + 5;//+5讓有一點屋檐的效果 const geometry = new THREE.BoxGeometry(baseLength + 2, width, 1); const texture = new THREE.TextureLoader().load("/img/tile.jpg"); texture.wrapS = texture.wrapT = THREE.RepeatWrapping; texture.repeat.set(2, 2); const material = new THREE.MeshPhongMaterial({ map: texture }); const mesh = new THREE.Mesh(geometry, material); mesh.rotateZ(THREE.MathUtils.degToRad(75)); mesh.rotateY(-Math.PI / 2); mesh.position.set(baseWidth / 3 - 1, 22, 0); mesh.name = "右屋頂"; group.add(mesh); return { roof: mesh, width };
} ``` 方法執行後如下圖,我們有了一個右邊的屋頂
如法炮製,再來一個左邊的屋頂
js
let { roof, width } = createRoof();
return
let leftRoof = roof.clone();
leftRoof.rotateX(THREE.MathUtils.degToRad(30));
leftRoof.position.set(-baseWidth / 3 + 1, 22, 0);
leftRoof.name = "左屋頂";
group.add(leftRoof);
隨後可以在畫面中看到如下圖,我們的房子,哦不,準確的說是倉庫已經出來了。。。
5、建立門
然後我們開始建立門,門的建立也是用的內建的BoxGeometry
幾何體。
新增一個createDoor
方法,如下
```js function createDoor() { //紋理貼圖 const texture = new THREE.TextureLoader().load("/img/door.jpg"); //門的大小、尺寸 const door = new THREE.BoxGeometry(10, 15, 0.5); const material = new THREE.MeshPhongMaterial({ map: texture, transparent: true, opacity: 1, }); const doorMesh = new THREE.Mesh(door, material); doorMesh.name = "門"; doorMesh.position.x = 5; group.add(doorGroup);
} ``` 呼叫後即可看到原本的門洞中出現了一扇門,如下圖
6、為場景新增點選
接下來我想做一點選開門的效果,那麼首先要獲取到滑鼠點選了哪些物體。很巧的是three.js為我們提供了一個Raycaster
類,用來檢測射線觸碰到了哪些物體。
新增如下程式碼
```js const raycaster = new THREE.Raycaster(); const pointer = new THREE.Vector2();
function onPointerMove(event) { // 將滑鼠位置歸一化為裝置座標。x 和 y 方向的取值範圍是 (-1 to +1) pointer.x = (event.clientX / width) * 2 - 1; pointer.y = -(event.clientY / height) * 2 + 1; } ``` 然後為canva新增點選事件監聽
```js canvas.addEventListener( "click", () => { const intersects = raycaster.intersectObjects(scene.children); console.log(intersects[0]); console.log("點選了", intersects[0]?.object?.name);
},
false
);
``
隨後我們點選場景中,在控制檯中便能清晰的打印出我們所點選的物體。說明:
intersectObjects`方法會返回射線經過的所有物體組成的陣列,陣列的第0位為離點選區域最近的物體,因此可以視為被點選的物體。
現在已經知道點選的是哪個物體,下面就來新增門的動畫效果
7、新增關門、開門動畫效果
調整一下對上節的方法,如下,匹配到點選的物體是門的時候再來觸發。
```js canvas.addEventListener( "click", () => { const intersects = raycaster.intersectObjects(scene.children); console.log(intersects[0]); console.log("點選了", intersects[0]?.object?.name); if (intersects[0]?.object?.name == "門") { // console.log(intersects[0].object.parent.rotation.y); let speed = 0.05; //再次點選關門 if (intersects[0].object.parent.rotation.y <= -2.5) { // console.log("關門"); let a = setInterval(() => { if (intersects[0].object.parent.rotation.y >= 0) { intersects[0].object.parent.rotation.y = 0; clearInterval(a); return; }
intersects[0].object.parent.rotation.y += speed;
}, 1000 / 60);
} else {
// console.log("開門");
let a = setInterval(() => {
if (intersects[0].object.parent.rotation.y <= -2.5) {
clearInterval(a);
return;
}
intersects[0].object.parent.rotation.y -= speed;
}, 1000 / 60);
}
}
},
false
);
``
這樣就能正確的運行了嗎?當然不,上述程式碼中讓門以y軸做旋轉,但是在three.js中,物體的旋轉軸為物體的中心,因此我們需要改變一下門的旋轉軸,使之在視覺上呈現出以旋轉中心的改變,下面改造一下
createDoor`方法,如下,
```js //建立門 function createDoor() { const texture = new THREE.TextureLoader().load("/img/door.jpg"); const door = new THREE.BoxGeometry(10, 15, 0.5); const material = new THREE.MeshPhongMaterial({ map: texture, transparent: true, opacity: 1, }); const doorMesh = new THREE.Mesh(door, material); // doorMesh.rotateY(Math.PI / 2); // doorMesh.position.set(-baseLength / 2, 7, 0);
doorMesh.name = "門";
//以下程式碼做出了更改 const doorGroup = new THREE.Group();//新增一個門的父級 doorGroup.name = "門的包裹"; doorGroup.position.set(-5, 8, baseLength / 2);//通過父級來改變門的旋轉軸 //現在這個是相對於父級 doorMesh.position.x = 5; doorGroup.add(doorMesh); group.add(doorGroup); return doorGroup; } ```
改造完後點擊門,會發現門繞著預期的旋轉軸打開了。如下圖
四、建立天空盒
這裡的天空盒非常的簡單。使用內建的SphereGeometry
幾何體建立一個與地面半徑一致的圓,然後載入貼圖
js
//天空盒
function createSkyBox() {
const texture = new THREE.TextureLoader().load("/img/sky.jpg");
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
// texture.repeat.set(1, 1);
const skyBox = new THREE.SphereGeometry(500, 100, 100);
const material = new THREE.MeshPhongMaterial({
map: texture,
side: THREE.BackSide,
});
const skyBoxMesh = new THREE.Mesh(skyBox, material);
scene.add(skyBoxMesh);
}
最終呈現出的效果如下圖
在最後你通過迴圈多建立幾個房子,像這樣
或者檢視文件切換成第一人稱控制器在自己建立的場景中遨遊。