效果
访问地址:
http://localhost:8080/Apps/Sandcastle/index.html?src=Camera%20Tutorial.html&label=Tutorials
通过键盘及鼠标控制相机
知识点
// Gets an ellipsoid describing the shape of this globe.
var ellipsoid = scene.globe.ellipsoid;
禁用系统的默认事件: 例如 旋转,平移,缩放等
// disable the default event handlers
scene.screenSpaceCameraController.enableRotate = false;
scene.screenSpaceCameraController.enableTranslate = false;
scene.screenSpaceCameraController.enableZoom = false;
scene.screenSpaceCameraController.enableTilt = false;
scene.screenSpaceCameraController.enableLook = false;
相机句柄
scene.screenSpaceCameraController
Gets the controller for camera input handling.
处理用户输入事件。可以添加自定义功能,以便在用户输入输入时执行。
var handler = new Cesium.ScreenSpaceEventHandler(canvas);
// 获取鼠标开始按下的位置
handler.setInputAction(function(movement) {
flags.looking = true;
mousePosition = startMousePosition = Cesium.Cartesian3.clone(movement.position);
}, Cesium.ScreenSpaceEventType.LEFT_DOWN);
// 鼠标开始移动
handler.setInputAction(function(movement) {
mousePosition = movement.endPosition;
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
// 鼠标左键抬起时,关闭查看视角
handler.setInputAction(function(position) {
flags.looking = false;
}, Cesium.ScreenSpaceEventType.LEFT_UP);
绑定按键按下和抬起的动作。
很优雅:
typeof flagName !== ‘undefined’
document.addEventListener('keydown', function(e) {
var flagName = getFlagForKeyCode(e.keyCode);
if (typeof flagName !== 'undefined') {
flags[flagName] = true;
}
}, false);
document.addEventListener('keyup', function(e) {
var flagName = getFlagForKeyCode(e.keyCode);
if (typeof flagName !== 'undefined') {
flags[flagName] = false;
}
}, false);
定时执行相关代码
// Gets the camera.
var camera = viewer.camera;
// 计时器,定时刷新,执行自定义函数处理
viewer.clock.onTick.addEventListener(function(clock) {
var width = canvas.clientWidth;
var height = canvas.clientHeight;
// 获取移动鼠标的坐标位置
// Coordinate (0.0, 0.0) will be where the mouse was clicked.
var x = (mousePosition.x - startMousePosition.x) / width;
var y = -(mousePosition.y - startMousePosition.y) / height;
// 将提供的笛卡尔转换为制图表示。笛卡尔在椭圆体的中心未定义。
var cameraHeight = ellipsoid.cartesianToCartographic(camera.position).height;
var moveRate = cameraHeight / 100.0;
相机移动的相关代码:
camera.lookRight(moveRate);
camera.lookUp(moveRate);
camera.moveForward(moveRate);
camera.moveBackward(moveRate);
camera.moveUp(moveRate);
camera.moveDown(moveRate);
camera.moveLeft(moveRate);
camera.moveRight(moveRate);
总结
- 禁用系统事件
- 通过 ScreenSpaceEventHandler 绑定鼠标事件处理函数; 通过 document.addEventListener 绑定键盘事件处理函数
- viewer.clock.onTick 更新 camera 相关操作