ThreeJS
Begin
To begin 3JS, we should use scene,camera,renderer
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
Geometry
The base logic to add cube to scene is:
- generate a geometric object
- set a material
- set a Mesh object, which group geo and mtr
- add to scene
- adjust position of camera
So, the key points are Geometry,Materail,Mesh , mesh should added to scene
animation
Animation in ThreeJS is not complicated, it use requestAniamtionFrame (RAF) to consecutively render animated graphic.
var animate = function () {
requestAnimationFrame( animate );
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render( scene, camera );
};
then, run animate()
NOTE
The first time I forgot to set size of render and I also need to add renderer to body
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
Draw some Lines in 3D
First, I should new a Geometry object, then I push Vector3 points to Vertices of geo object. Using specific material, and group in Line object
geometry.vertices.push(new THREE.Vector3(x,y,z))
var material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
var line = new THREE.Line(geo, material)
Buffer
Sometimes we should use cache (缓存), to quickly load 3D object, so we use Buffer to save the location of point, Vertices. Because Javascript’s Array is not real array, so we use 强类型 array to save data.
let arr = new Float32Array([1,2,3])
This piece of code create a 浮点数 array, which can quickly use.
load own 3D object
ThreeJS allow user load own object. Blender 2.8 can export usable object as GLTF, we should reference a script to use a GLTF loader. Then implement a GLTFLoader class:
let loader = new THREE.GLTFLoader();
loader.load(
"js/myObject.glb",
function(gltf){
let scene = gltf.scene // it's a scece
let model = scene.children // there would be a Array, all of object in there
s.add(model) // s is our global variable
},
function(xhr){
console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' ); //异步操作
}
)
Another thing we should note is, the model could be really large, or far away global center, so our camera would not shot that, so it will not appear . The solution is, move it to global center.