threejs基础

125 阅读1分钟

创建 场景

const scene = new THREE.Scene()

创建 几何体

const geometry = new THREE.BoxGeometry(100, 100, 100)

设置几何体 材质

const material = new THREE.MeshLambertMaterial({
  color: 0x00ffff, // 材质颜色
  transparent: true, // 设置是否透视
  opacity: 0.5 // 透明度
})

创建网格模型

const mesh = new THREE.Mesh(geometry, material)
mesh.position.set(0, 0, 0) // 默认在坐标原点(0,0,0)

往场景中添加网格模型

scene.add(mesh) // 模型对象插入场景中

在场景添加辅助三维坐标

// 创建 三维坐标轴 rgb == xyz
const axesHelper = new THREE.AxesHelper(130)
scene.add(axesHelper)

创建光源

// 创建光源
const light = new THREE.PointLight(0xffffff, 1.5)
light.position.set(100, 100, 70)
scene.add(light)
// 设置光源可视化辅助体
const pointHelper = new THREE.PointLightHelper(light, 3, 0xff0000)
scene.add(pointHelper)

创建透视相机对象

const camera = new THREE.PerspectiveCamera(30, width / height, 0.1, 100000)
// 相机的视线坐标
camera.position.set(200, 200, 200)
// 设置 轨道相机的时候要把  orbitcontrols的观察目标点 设置到和lookAt 一直否则 默认观察点会被默认成(0,0,0)
camera.lookAt(0, 0, 0) // 相机观察的中心坐标

设置 输出canvas画布大小

// 相机输出canvas画布的大小
const width = window.innerWidth
const height = window.innerHeight
// 渲染器
const renderer = new THREE.WebGLRenderer()
window.onresize = function () {
  renderer.setSize(window.innerWidth, window.innerHeight)
  camera.aspect = window.innerWidth / window.innerHeight
  camera.updateProjectionMatrix()
}

将场景渲染到画布当中

// 通过renderer中的domElement属性获取  生成的canvas画布,添加到到网页中
document.body.appendChild(renderer.domElement)