三维开发中,有时候需要用到鼠标拖拽的方式去绘制圆形和矩形,甚至可以在绘制的时候实时显示绘制图形的面积或者周长等几何信息。那么话不多说,先看效果:
动图我们可以看到绘制显示是根据鼠标实时生成的,主要的代码为控制鼠标事件
//鼠标左键
handler.setInputAction(function (event) {
if (Cesium.defined(earthPosition)) {
if (activeShapePoints.length === 0) {
floatingPoint = createPoint(earthPosition);
activeShapePoints.push(earthPosition);
var dynamicPositions = new Cesium.CallbackProperty(function () {
if (drawingMode === 'polygon') {
return new Cesium.PolygonHierarchy(activeShapePoints);
}
return activeShapePoints;
}, false);
activeShape = drawShape(dynamicPositions); //绘制动态图,传入function
}
activeShapePoints.push(earthPosition);
createPoint(earthPosition);
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
//鼠标移动
handler.setInputAction(function (event) {
if (Cesium.defined(floatingPoint)) {
var newPosition = viewer.scene.pickPosition(event.endPosition);
if (Cesium.defined(newPosition)) {
floatingPoint.position.setValue(newPosition);
activeShapePoints.pop();
activeShapePoints.push(newPosition);
}
}
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
还有就是绘制的时候计算图形的半径和边长等信息
//绘制图形
function drawShape(positionData) {
var shape;
if (drawingMode === 'line') {
shape = viewer.entities.add({
polyline: {
positions: positionData,
clampToGround: true,
width: 3
}
});
} else if (drawingMode === 'polygon') {
shape = viewer.entities.add({
polygon: {
hierarchy: positionData,
material: new Cesium.ColorMaterialProperty(Cesium.Color.WHITE.withAlpha(0.7))
}
});
} else if (drawingMode === 'circle') {
//当positionData为数组时绘制最终图,如果为function则绘制动态图
var value = typeof positionData.getValue === 'function' ? positionData.getValue(0) : positionData;
shape = viewer.entities.add({
position: activeShapePoints[0],
name: 'Blue translucent, rotated, and extruded ellipse with outline',
type: 'Selection tool',
ellipse: {
semiMinorAxis: new Cesium.CallbackProperty(function () {
//半径 两点间距离
var r = Math.sqrt(Math.pow(value[0].x - value[value.length - 1].x, 2) + Math.pow(value[0].y - value[value.length - 1].y, 2));
return r ? r : r + 1;
}, false),
semiMajorAxis: new Cesium.CallbackProperty(function () {
var r = Math.sqrt(Math.pow(value[0].x - value[value.length - 1].x, 2) + Math.pow(value[0].y - value[value.length - 1].y, 2));
return r ? r : r + 1;
}, false),
material: Cesium.Color.BLUE.withAlpha(0.5),
outline: true
}
});
} else if (drawingMode === 'rectangle') {
//当positionData为数组时绘制最终图,如果为function则绘制动态图
var arr = typeof positionData.getValue === 'function' ? positionData.getValue(0) : positionData;
shape = viewer.entities.add({
name: 'Blue translucent, rotated, and extruded ellipse with outline',
rectangle: {
coordinates: new Cesium.CallbackProperty(function () {
var obj = Cesium.Rectangle.fromCartesianArray(arr);
//if(obj.west==obj.east){ obj.east+=0.000001};
//if(obj.south==obj.north){obj.north+=0.000001};
return obj;
}, false),
material: Cesium.Color.RED.withAlpha(0.5)
}
});
}
return shape;
}
到这,基本就OK了
全部代码见资源