Search code examples
javascriptcesiumjs

Detect and react to custom keyboard input events


How should I go about listening to keypresses, keydowns, and keyups of, say, A or Alt+A?

From the documentation of ScreenSpaceEventHandler(element).setInputAction(action, type, modifier), it follows that type and modifier must be of types ScreenSpaceEventType and KeyboardEventModifier respectively, which amount to a rather restricted set of events available for my purpose.


Solution

  • The ScreenSpaceEventHandler is only for input events that involve screen space: mouse, touch, and pointer events. For raw keyboard events like ALT + A, just use JavaScript native keyboard events such as keydown, keypress, etc. You don't need Cesium's help to receive these events.

    You will, however, need to apply a tabindex to the Cesium canvas, to enable it to receive the input focus:

    var viewer = new Cesium.Viewer('cesiumContainer');
    var canvas = viewer.canvas;
    canvas.setAttribute('tabindex', '0'); // needed to put focus on the canvas
    

    You can find a complete working example of this in the Cesium Camera Tutorial. Click on the globe itself, and then use W, A, S, D to move the camera.