25 Apr 2025

Selecting multiple elements in the Viewer

thumbnail

Introduction

In this blog, we'll share a way to enable your users to select multiple elements in the Viewer by just holding the CTRL key.

We will achieve that through an Extension that leverages the ToolInterface.

How it works

To make this work, we can use the logic below in our tool, which overrides the default single-click behavior from the Viewer:

handleSingleClick(event, button) {
      const currentSelection = this.viewer.getSelection();
      //check if ctrl key is pressed
      if (event.ctrlKey) {
          this.selection.push(...currentSelection)
      }
      else{
        const castResult = this.viewer.clientToWorld(event.canvasX, event.canvasY);
        this.selection = !!castResult?.dbId? [castResult.dbId]: []; // Reset the selection if ctrl key is not pressed
      }
      this.viewer.select(this.selection); 
      //Return true so it doesn't call the default behavior of the viewer (which is to select the object under the mouse cursor)
      return true;
  }
}

This method checks if the CTRL key is being pressed every time we click in our canvas.

If so, it aggregates the current selected element to an array in our tool and then selects this array.

If you click without pressing the CTRL key, then it uses the clientToWorld method to select only the current element, and erases the previously aggregated IDs from our tool.

Calling this method each time we click the canvas, we have the experience below:

You can find the complete source code and a live demo below:

LIVE DEMO

SOURCE

Related Article