官网
three.js,文档在documentation
中
ambientcg材质网:免费下载材质包
示例
import * as THREE from 'three'
// 创建场景
const scene = new THREE.Scene()
// scene.background = new THREE.Color('rgb(242, 243, 244)') // 背景颜色
const loader = new THREE.TextureLoader()
loader.load('../img/01.jpg', function (texture) {
scene.background = texture
// 加载图片为背景,如果不使用动画requestAnimationFrame(),
// 需要在此处手动执行一次renderer.render(scene, camera),原因是此次异步,后出现
})
// 创建相机
const camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
0.1,
1000
)
camera.position.z = 7 // 观察位置
camera.position.x = 2
camera.position.y = 2
camera.lookAt(0, 0, 0) // 观察方向
// 创建渲染器
const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)
// 物体
const cube = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshBasicMaterial()
)
scene.add(cube) // 可以添加任意数量物体,如:scene.add(cube, cube2)
const cube2 = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshBasicMaterial({
color: 0xff0000
})
)
cube2.position.x = 2
scene.add(cube2)
function animate() {
requestAnimationFrame(animate)
cube.rotation.x += 0.01
cube.rotation.y += 0.01
renderer.render(scene, camera)
}
animate()
场景
Scene:容器
相机
Camera:观察
- 透视相机:模拟人眼
- 正交相机
- 立方相机
- 立体相机
位置设置
方式一:
camera.position.z = 7
camera.position.x = 2
camera.position.y = 2
camera.lookAt(0, 0, 0) // 观察点
方式二:
camera.position.set(2, 2, 7)
camera.lookAt(0, 0, 0) // 观察点
圆周运动
let angle = 0
const radius = 9 // 距离
function animate() {
requestAnimationFrame(animate)
cube.rotation.x += 0.01
cube.rotation.y += 0.01
angle += 0.005
camera.position.x = radius * Math.cos(angle)
camera.position.z = radius * Math.sin(angle)
camera.lookAt(0, 0, 0)
renderer.render(scene, camera)
}
渲染器
Renderer:将场景和相机组合
可以指定渲染容器:
<canvas class="box"></canvas>
const renderer = new THREE.WebGLRenderer({
canvas: document.querySelector('.box')
})
抗锯齿
const renderer = new THREE.WebGLRenderer({
antialias: true
})
物体复制
let plane2 = plane.clone()
plane2.position.set(20, 0, 0)
scene.add(plane2)