threejs源码下载地址:Releases · mrdoob/three.js · GitHub
threejs主要分为场景,照相机,渲染器,控件
完整的步骤创建场景,创建几何体和材质,创建模型和灯光加在场景中,创建照相机和渲染器,渲染,加入控件实现拖拽,拖动和缩放。
完整实例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./three.js-r139/build/three.js"></script>
<script src="./three.js-r139/examples/js/controls/OrbitControls.js"></script>
</head>
<body>
<script >
// 创建场景
var scene = new THREE.Scene()
// 创建几何体
const geometry = new THREE.BoxGeometry(40,40,40)
// 创建材质
const material = new THREE.MeshPhongMaterial({
color: 0x4fbbff
})
// 模型与材质建立连接
const mesh = new THREE.Mesh(geometry,material)
mesh.position.set(0,10,0);
// 将模型放在场景中
scene.add(mesh)
// 世界坐标
const axesHelper = new THREE.AxesHelper( 100 );
scene.add( axesHelper );
//灯光 环境光
const ambient = new THREE.AmbientLight(0x00ffff,1)
scene.add(ambient)
// 点光源
const light = new THREE.PointLight( 0xffffff, 1 );
light.position.set(-400, -200, -300);
scene.add( light );
// 点光源辅助
const pointLightHelper = new THREE.PointLightHelper( light, 1 );
scene.add( pointLightHelper );
// 创建相机
const width = 800
const height = 500
const camera = new THREE.PerspectiveCamera(45,width/height,1,1000)
camera.position.set(200,200,200)
camera.lookAt(10, 10, 10 )
// 渲染
const render = new THREE.WebGLRenderer()
render.setSize(width,height)
// 相机与场景建立连接
render.render(scene,camera)
document.body.appendChild( render.domElement );
// 相机控件实现旋转缩放
const controls = new THREE.OrbitControls(camera, render.domElement)
controls.addEventListener('change' , function() {
render.render(scene,camera)
})
</script>
</body>
</html>
场景
场景sence的结构像是树形,他的子集包括了模型和灯光
// 创建场景
var scene = new THREE.Scene()
一.模型
模型分为三种,点模型,线模型,网格模型
线模型又分为了line,lineloop,linesegments
//点模型对象
const points = new THREE.Points(geometry, material);
// 创建线模型对象
const line = new THREE.Line(geometry, material);
// 闭合线条
const line = new THREE.LineLoop(geometry, material);
//非连续的线条
const line = new THREE.LineSegments(geometry, material);
//网格模型对象
const mesh= new THREE.Mesh(geometry, material);
而组成模型的需要两个参数,geometry和material,即几何体和材质
材质按模型类型分为点,线,网格材质
在网格材质中,按是否受光影响分为基础材质(不受光影响),高光漫反射(受光影响),物理材质(PBR材质,更复杂真实)
二.灯光
//点光源
const light = new THREE.PointLight( 0xffffff, 1 );
light.position.set(-400, -200, -300);
scene.add( light );
//辅助
const pointLightHelper = new THREE.PointLightHelper( light, 1 );
scene.add( pointLightHelper );
// 平行光
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
// 设置光源的方向:通过光源position属性和目标指向对象的position属性计算
directionalLight.position.set(80, 100, 50);
// 方向光指向对象网格模型mesh,可以不设置,默认的位置是0,0,0
directionalLight.target = mesh;
//辅助
const DirectionalLightHelper = new THREE.DirectionalLightHelper( light, 1 );
scene.add( DirectionalLightHelper );
scene.add(directionalLight);