0%

15 组合曲线 - Threejs入门

通过组合曲线 CurvePath 对象,可以把直线、圆弧、贝塞尔等线条拼接为一条曲线。 [ 练一练 ] [ 看一看 ]

整体思路很简单,LineCurve 创建两条直线线段,ArcCurve 绘制一段圆弧线,然后把两段直线和一段圆弧线,通过组合曲线的 CurvePath.curves 属性拼接起来。

示例代码

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
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)

// 组合曲线
const R = 2 //圆弧半径
const H = 5 //直线部分高度

// 直线1
const line1 = new THREE.LineCurve(
new THREE.Vector2(R, H),
new THREE.Vector2(R, 0)
)

// 圆弧
const arc = new THREE.ArcCurve(0, 0, R, 0, Math.PI, true)

// 直线2
const line2 = new THREE.LineCurve(
new THREE.Vector2(-R, 0),
new THREE.Vector2(-R, H)
)

// CurvePath创建一个组合曲线对象
const curvePath = new THREE.CurvePath()
//line1, arc, line2拼接出来一个U型轮廓曲线,注意顺序
curvePath.curves.push(line1, arc, line2)

const geo = new THREE.BufferGeometry()
geo.setFromPoints(curvePath.getSpacedPoints(10))
const mat = new THREE.LineBasicMaterial()
const line = new THREE.Line(geo, mat)
scene.add(line)

const controls = new OrbitControls(camera, app)

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

演示效果