Three.js 總結一


三要素:scene(場景)、camera(相機)、renderer(渲染器)

scene變量是一個容器,用來保存並跟蹤所有我們想渲染的物體。

camera變量定義了我們能夠在渲染好的scene里看到什么。

renderer對象負責計算制定相機角度下,瀏覽器中scene的樣子。

 

三維對象:Plane(平面)、Cube(方塊)、Sphere(球體)、Camera(相機)、Axes(軸) 

scene

scene.add()  scene.remove()  在場景中添加移除物體

scene.children()   獲取場景中所有子對象的列表

scene.getChildByName()    利用name屬性,獲取場景中某個特定的物體

霧化(兩種方式)

Fog(hex,near,far)    FogExp2(hex,density)

scene.fog = new THREE.Fog(0xffffff,0.015,100)  
scene.fog = new THREE.FogExp2(0xffffff,0.015)

Fog:  properties:name  color  near(1)  far(1000)  methods: .clone()  .toJSON() 

FogExp2: properties:name color density(0.00025)  methods: .clone()  .toJSON() 

renderer  

var renderer = new THREE.WebGLRenderer()
renderer.setClearColorHex(0xEEEEEE)
renderer.setSize(window.innerWidth,window.innerHeight)
renderer.shadowMapEnabled = true

setClearColor()      設置renderer背景色      

setSize()        設置scene渲染成多大尺寸

shadowMapEnabled  設置是否有陰影   

 

axes  坐標軸

var axes = new THREE.AxisHelper(20)
scene.add(axes)

 

創建平面

定義面板尺寸,寬60高20。創建材質,顏色。把這兩個對象合並到名為plane的Mesh對象中。

添加到場景前 首先放置到合適的位置。 先將它繞着x軸旋轉90度,然后position定義它在場景中的位置。

var planeGeometry = new THREE.PlaneGeometry(60,20)
var planeMaterial = new THREE.MeshBasicMaterial({color:0xcccccc})
var plane = new THREE.Mesh(planeGeometry,planeMaterial)
plane.rotation.x = -0.5*Math.PI
plane.position.x = 15
plane.position.y = 0
plane.position.z = 0
scene.add(plane)

 

創建光源

var spotLight = new THREE.SpotLight(0xffffff)
spotLight.position.set(-40,60,-10)
scene.add(spotLight)

不同材質對光源的反應不同,基礎材質(MeshBasicMaterial)不會對場景中的光源產生反應,只會以制定的顏色渲染物體。

 MeshLambertMaterial,MeshphongMaterial對光源有反應。

 

創建陰影

1、renderer.shadowMapEnabled = true

2、哪個物體接受陰影 哪個物體投射陰影  plane.receiveShadow = true cube.castShadow = true

3、定義光源 不是所有的光源都能產生陰影 spotLight.castShadow = true

 

引入requestAnimationFrame()方法

通過它你可以指定一個函數,按照瀏覽器定義的時間間隔調用。

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

遞歸調用,讓動畫持續運行。在整個場景創建完畢后,調用一次renderScene()函數來啟動動畫。

document.getElementById("WebGL-output").appendChild(renderer.domElement)
renderScene()

輔助庫:檢測動畫運行的幀頻。當我們顯示動畫時,該庫可以在一個小圖片里顯示每秒顯示的幀數

<script src="../libs/stats.js"></script>
<div id="Stats-output"></div>
function initStats(){
  var stats = new Stats()
  stats.setNode(0)
  stats.domElement.style.position = 'absolute'
  stats.domElement.style.left = '0px'
  stats.domElement.style.top = '0px'      
document.getElementById("Statsoutput").appendChild(stats.domElement)   return stats }

$(function(){
  var stats = initStats()
})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM