# 三.chaikin-smooth
前言
工作中有时为了线段看起来更美观,需要对线段进行顺滑处理,前端比较常见的处理方式,一个是通过 turfjs(前端拓扑工具)和 chaikin-smooth(专门处理平滑曲线) ,后者体积很小,因此笔者工作中使用后者
# 1.绘制平滑曲线
使用chaikin-smooth
绘制平滑曲线
查看代码详情
<template>
<div>
<div ref="map" class="map"></div>
<form class="form-inline">
<label for="shall-smoothen">绘制平滑几何图形?</label>
<input ref="shallsmoothen" type="checkbox" checked /><br />
<label for="iterations">平滑次数</label>
<input
style="width: 250px"
type="range"
ref="iterations"
min="2"
max="10"
step="1"
value="5"
/>
</form>
</div>
</template>
<script>
export default {
mounted() {
let {
interaction: { Draw },
Map,
View,
layer: { Tile: TileLayer, Vector: VectorLayer },
source: { OSM, Vector: VectorSource },
style: Style,
} = ol;
function makeSmooth(path, numIterations) {
numIterations = Math.min(Math.max(numIterations, 1), 10);
while (numIterations > 0) {
path = smooth(path);
numIterations--;
}
return path;
}
const vectorSource = new VectorSource({});
const map = new Map({
layers: [
new TileLayer({
source: new OSM(),
opacity: 0.5,
}),
new VectorLayer({
source: vectorSource,
}),
],
target: this.$refs.map,
view: new View({
center: [1078373.595, 6871994.591],
zoom: 5,
}),
});
const shallSmoothen = this.$refs.shallsmoothen;
const numIterations = this.$refs.iterations;
const draw = new Draw({
source: vectorSource,
type: "LineString",
});
map.addInteraction(draw);
draw.on("drawend", function (event) {
if (!shallSmoothen.checked) {
return;
}
const feat = event.feature;
const geometry = feat.getGeometry();
const coords = geometry.getCoordinates();
const smoothened = makeSmooth(
coords,
parseInt(numIterations.value, 10) || 5
);
geometry.setCoordinates(smoothened);
});
},
};
</script>
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
← 二.turf.js 四.topojson →