0%

14 样条曲线和贝塞尔曲线 - Threejs入门

对于一个不规则的曲线,很难用圆或者椭圆去描述,用样条曲线和贝塞尔曲线来表达是更好的方式。 [ 练一练 ] [ 看一看 ]

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import * as THREE from 'three'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'

const scene = new THREE.Scene()

const camera = new THREE.PerspectiveCamera(
60,
window.innerWidth / window.innerHeight,
0.1,
100
)
camera.position.z = 30

const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
app.appendChild(renderer.domElement)

// 三维样条曲线
// 三维向量Vector3创建一组顶点坐标
const arr = [
new THREE.Vector3(-5, 2, 9),
new THREE.Vector3(-1, 4, 4),
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(6, -6, 0),
new THREE.Vector3(7, 0, 8),
]
const curve = new THREE.CatmullRomCurve3(arr)

const geo = new THREE.BufferGeometry()
geo.setFromPoints(curve.getPoints(50))
const mat = new THREE.LineBasicMaterial()
const line = new THREE.Line(geo, mat)
scene.add(line)

// 贝塞尔曲线
// p1、p2、p3表示三个点坐标
// p1、p3是曲线起始点,p2是曲线的控制点
const p1 = new THREE.Vector2(-8, 0)
const p2 = new THREE.Vector2(2, 10)
const p3 = new THREE.Vector2(8, 0)
const curve2 = new THREE.QuadraticBezierCurve(p1, p2, p3)

const geo2 = new THREE.BufferGeometry()
geo2.setFromPoints(curve2.getPoints(50))
const mat2 = new THREE.LineBasicMaterial()
const line2 = new THREE.Line(geo2, mat2)
scene.add(line2)

const controls = new OrbitControls(camera, app)

renderer.setAnimationLoop(() => {
renderer.render(scene, camera)
})

演示效果