Konva – rubber band selection

Using a click-drag-rect to select objects visually is a staple of graphics UX – this is one way to do it with Konva.

TLDR: See the demo code here at CodePen.

The runner rectangle in use

The technique is straightforward. We use the following events to manage the process.

  • stage.mousedown – note the start point – this is where the rubber rect starts from
  • stage.mousemove – this gives us a new end point each time it fires. Each time we can redraw the rubber rect.
  • stage.mouseup – this tells us the user completed to rubber band process, and we can hide the rubber band

The rubber rect itself is just another plain Konva.Rect with no fill and with its stroke set with a dashed pattern.

The only part of this worthy of more note is the fact that we use the following methods to get the shape position rectangles and the point position, both relative to the stage. Konva gives us various methods for getting shape rect and position – we want to ensure that whichever we select, they are relative to the same container!

// position of shape relative to stage
const shapePos = shape.getClientRect({relativeTo: stage}) 

// position of pointer relative to stage
const mousePos = stage.getRelativePointerPosition()

This means that we are immune from the effects of scale, and of stage or layer position changes.

Summary

We’ve seen a simple approach to a rubber selection rectangle for Konva, and learned how to get shape and pointer positions relative to the stage. Both useful techniques to have in your kit bag.

Thanks for reading.

VW March 2023.

Photo credit: Roberto Sorin and unspalsh.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: