原文链接及内容

这个例子使用了npm包chaikin-smooth,它使用了Chaikins算法来平滑绘制的线条。从在地图上画画开始,一旦完成绘图,该要素的几何形状将按照上述滑块配置进行平滑处理。
main.js
代码如下:
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
| import Draw from 'ol/interaction/Draw.js'; import Map from 'ol/Map.js'; import View from 'ol/View.js'; import {OSM, Vector as VectorSource} from 'ol/source.js'; import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer.js';
import smooth from 'chaikin-smooth';
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: 'map', view: new View({ center: [1078373.595, 6871994.591], zoom: 5, }), });
const shallSmoothen = document.getElementById('shall-smoothen'); const numIterations = document.getElementById('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); });
|
界面布局文件index.html
代码如下:
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
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Smoothing lines using Chaikins algorithm</title> <link rel="stylesheet" href="node_modules/ol/ol.css"> <style> .map { width: 100%; height: 400px; } </style> </head> <body> <div id="map" class="map"></div> <form> <label for="shall-smoothen">Smooth drawn geometry?</label> <input id="shall-smoothen" type="checkbox" checked><br> <label for="iterations">Number of smoothings</label> <input style="width: 250px;" type="range" id="iterations" min="2" max="10" step="1" value="5"> </form> <script src="https://cdn.jsdelivr.net/npm/elm-pep@1.0.6/dist/elm-pep.js"></script> <script type="module" src="main.js"></script> </body> </html>
|