快速过一下基本用法
文章目录
入门
01 场景
//场景、相机和渲染器
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 );
//加物体
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;//设置位置
function animate() {
//使渲染器能够在每次屏幕刷新时对场景进行绘制的循环,当用户切换到其它的标签页时,它会暂停(跟setInterval差不多)。不然以上代码画面是空的
requestAnimationFrame( animate );
cube.rotation.x += 0.01;//动画
cube.rotation.y += 0.01;//动画
renderer.render( scene, camera );//渲染
}
animate();
02 兼容性检查
引入WebGL.js
if (WebGL.isWebGLAvailable()) {
// Initiate function or other initializations here
animate();
} else {
const error = WebGL.getWebGLErrorMessage();
console.error(error)
}
03 画线
const scene = new THREE.Scene();//场景
const renderer = new THREE.WebGLRenderer();//渲染器
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
const camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 500 );
camera.position.set( 0, 0, 100 );//相机位置
camera.lookAt( 0, 0, 0 );//相机朝向
const material = new THREE.LineBasicMaterial( {
color: 0x0000ff } );//材质
//构建三维几何体
const points = [];
points.push( new THREE.Vector3( - 10, 0, 0 ) );//Vector3--三维空间中的向量
points.push( new THREE.Vector3( 0, 10, 0 ) );//Vector3--三维空间中的向量
points.push( new THREE.Vector3( 10, 0, 0 ) );//Vector3--三维空间中的向量
//线是画在每一对连续的顶点之间的,不闭合
const geometry = new THREE.BufferGeometry().setFromPoints( points );//BufferGeometry--定义3D几何体
const line = new THREE.Line( geometry, material );//物体=几何体+材质
scene.add( line );//加到场景中
renderer.render<