Three.js#01#入門

環境搭建

根據官方教程搭建開發環境。

項目根目錄有index.html、main.js、public/三個文件(夾)

然後把nodejs16x卸載了,因爲官方貌似今年底即將停止維護,換成了nodejs18x並且設置鏡像:

npm install -g cnpm --registry=https://registry.npmmirror.com
npm config set registry https://registry.npm.taobao.org

這樣有時候npm不好使可以試下cnpm,第二條指令好像可以解決npx速度慢的問題。繼續遵循教程:

# three.js
npm install --save three

# vite
npm install --save-dev vite

然後通過npx vite把項目跑起來。

項目寫好之後可以通過npx vite build打包。

基本概念和參數

遵循教程的第一段代碼:

import * as THREE from 'three';

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

首先講PerspectiveCamera的構造函數。

PerspectiveCamera構造函數的第一個參數是FOV(the field of view)視野,單位是度。決定可以看到的場景範圍。FOV值越大,相機拍攝的範圍就越廣,場景看起來就更小,反之亦然。

第二個是縱橫比。您幾乎總是希望使用元素的寬度除以高度,否則您將得到與在寬屏電視上播放老電影時相同的結果-圖像看起來被壓扁了。

接下來是近裁剪面和遠裁剪面(near and far clipping plane): 它們是用來控制渲染的範圍的。這意味着,距離相機遠於far值或近於near值的物體將不會被渲染。你現在不必擔心這個,但你可能想在你的應用程序中使用其他值來獲得更好的性能。

Next up is the renderer. In addition to creating the renderer instance, we also need to set the size at which we want it to render our app. It's a good idea to use the width and height of the area we want to fill with our app - in this case, the width and height of the browser window. For performance intensive apps, you can also give setSize smaller values, like window. innerWidth/2 and window. innerHeight/2, which will make the app render at quarter size.

const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );

camera.position.z = 5;

我們需要的第三個東西是Mesh。Mesh是一個對象,它採用一個幾何圖形,並應用一個材質,然後我們可以將其插入到我們的場景中,並自由移動。

默認情況下,當我們調用scene.add()時,我們添加的東西將被添加到座標(0,0,0)中。這將導致相機和立方體都在對方的內部。爲了避免這種情況,我們簡單地將相機移出一點。

如果將上面的代碼複製到我們前面創建的HTML文件中,您將看不到任何內容。這是因爲我們實際上還沒有渲染任何東西。爲此,我們需要所謂的渲染或動畫循環。

function animate() {
	requestAnimationFrame( animate );
	renderer.render( scene, camera );
}
animate();

這將創建一個循環,導致渲染器在每次屏幕刷新時繪製場景(在典型的屏幕上,這意味着每秒60次)。如果你是在瀏覽器中編寫遊戲的新手,你可能會說“爲什麼我們不直接創建一個setInterval呢?”事實上,我們可以這樣做,但是requestAnimationFrame有很多優點。也許最重要的一點是,當用戶導航到另一個瀏覽器選項卡時它會暫停因此不會浪費他們寶貴的處理能力和電池壽命。

Loading-3D-models

https://threejs.org/docs/index.html#manual/en/introduction/Loading-3D-models

Libraries and Plugins

https://threejs.org/docs/index.html#manual/en/introduction/Libraries-and-Plugins

Useful links

https://threejs.org/docs/index.html#manual/en/introduction/Useful-links

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章