手绘
手绘示例。 绘制 编辑 手绘 矢量
本示例演示手绘模式下的 ol/interaction/Draw。在手绘过程中,拖动时会持续添加点。设置 freehand: true 可启用手绘模式。注意,手绘模式也可以通过 freehandCondition 选项有条件地启用。例如,要使用 Shift 键切换手绘模式,可以使用 freehandCondition: shiftKeyOnly。
main.js
js
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import Draw from 'ol/interaction/Draw.js';
import TileLayer from 'ol/layer/Tile.js';
import VectorLayer from 'ol/layer/Vector.js';
import OSM from 'ol/source/OSM.js';
import VectorSource from 'ol/source/Vector.js';
const raster = new TileLayer({
source: new OSM(),
});
const source = new VectorSource({wrapX: false});
const vector = new VectorLayer({
source: source,
});
const map = new Map({
layers: [raster, vector],
target: 'map',
view: new View({
center: [-11000000, 4600000],
zoom: 4,
}),
});
const typeSelect = document.getElementById('type');
const freehandCheckbox = document.getElementById('freehand');
let draw; // 全局变量,以便稍后移除
function addInteraction() {
if (typeSelect.value !== 'None') {
draw = new Draw({
source: source,
type: typeSelect.value,
freehand: freehandCheckbox.checked,
});
map.addInteraction(draw);
}
}
/**
* 处理 change 事件。
*/
typeSelect.onchange = function () {
map.removeInteraction(draw);
addInteraction();
};
/**
* 处理 change 事件。
*/
freehandCheckbox.onchange = function () {
if (draw) {
draw.setFreehand(freehandCheckbox.checked);
}
};
addInteraction();index.html
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>手绘绘制</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="type">几何类型 </label>
<select id="type">
<option value="LineString">LineString</option>
<option value="Polygon">Polygon</option>
<option value="Circle">Circle</option>
<option value="None">None</option>
</select>
<label for="freehand">启用手绘</label>
<input type="checkbox" id="freehand" checked />
</form>
<script type="module" src="main.js"></script>
</body>
</html>package.json
json
{
"name": "draw-freehand",
"dependencies": {
"ol": "10.11.0"
},
"devDependencies": {
"vite": "^8.1.5"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}