msc*_*c87 15 javascript undo openlayers-3
我需要在我的网络应用程序中使用一项功能来撤消最后一点.已经有一些解决方案,如这对于给定的问题,它可以处理它在一定程度上:
var undo = false; // set this to true in the Esc key handler
var draw = new ol.interaction.Draw({
// ...
geometryFunction: function(coords, geom) {
if (!geom) {
geom = new ol.geom.LineString(null);
}
if (undo) {
if (coords.length > 1) {
coords.pop();
}
undo = false;
}
geom.setCoordinates(coords);
return geom;
}
});
Run Code Online (Sandbox Code Playgroud)
但似乎有一个我无法弄清楚的错误.
使用这个plunker你可以尝试我要解释的内容:
如果你绘制一条带有一些顶点的线然后撤消(点击ESC)直到线上的最后一个点被移除,然后在刚刚撤消的同一点完成(或接近足够),最后一段将被删除,为什么?
由数字解释:
1-绘制线要素
我试了好几次就发生了.如果添加一个不接近移除的点或添加多个点,则不会发生这种情况.
编辑
似乎OL3检查几何的最后两个坐标,如果它们相同则决定完成绘图会话,并删除最后一个.我尝试了下面的代码:
function geometryChange(coordinates, geometry){
if (!geometry) {
geometry = new ol.geom.LineString(null);
}
if (undo){
var coords = geometry.getCoordinates();
console.info(coords);
console.info(coordinates);
var diff = coordinates.length - coords.length;
if (diff > 0) {
var lastCoordinates= coordinates[coordinates.length-1];
console.info(coordinates);
coordinates.splice(coordinates.length - (diff+1), diff,lastCoordinates);
console.info(coordinates);
coordinates.pop();
console.info(coordinates);
undo=false;
if (coords.length === 1){
undone=true;
lineStringdraw.finishDrawing();
undone=false;
var emptyFeature = vector2.getSource().getFeatures()[vector2.getSource().getFeatures().length-1];
vector2.getSource().removeFeature(emptyFeature);
featureID-=1;
}
}
}
//console.info(coordinates);
geometry.setCoordinates(coordinates);
//coordinates= geometry.getCoordinates();
return geometry;
}
Run Code Online (Sandbox Code Playgroud)
结果更有趣.当我撤消最后一点时,当我想添加一个接近该点的点(没有用双击完成该行)时,OL假定绘图已完成并触发drawend事件(我将此事件用于某些目的但令人惊讶地被无缘无故地触发).
尝试更改您的这段代码:
var keydown = function(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode === 27 && drawing === true){ //esc key
var geom = drawing_feature.getGeometry();
geom.setCoordinates(geom.getCoordinates().slice(0, -1));
}
};
Run Code Online (Sandbox Code Playgroud)
对此:
var keydown = function(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode === 27 && drawing === true){ //esc key
var geom = drawing_feature.getGeometry();
var coordsLength = geom.getCoordinates().length;
geom.setCoordinates(geom.getCoordinates().slice(0, coordsLength-1));
}
};
Run Code Online (Sandbox Code Playgroud)
如果您可以使用该removeLastPoint方法,请尝试以下操作
var keydown = function(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode === 27 && drawing === true){ //esc key
draw.removeLastPoint();
}
};
Run Code Online (Sandbox Code Playgroud)