Shape snapping with React Konva while building NeetoWireframe

Ajmal Noushad

Ajmal Noushad

May 17, 2023

Introduction

Shape snapping is a feature in software that allows shapes or objects to be automatically aligned or adjusted to a particular grid when they are moved or resized. This feature helps to ensure that shapes are properly aligned and positioned in relation to other shapes, making it easier to build design where things are properly aligned.

We needed "shape snapping" in NeetoWireframe. NeetoWireframe is a tool for creating interactive wireframes and prototypes. neetoWirefame is one of the various tools being built by neeto.

NeetoWireframe uses React Konva to build wireframes and prototypes. React Konva is a JavaScript library that provides a React component interface to the Konva library, a powerful 2D drawing library for the web. React Konva enables developers to create and manipulate complex graphics and visualizations in a declarative and efficient way using familiar React patterns. With React Konva, developers can easily create canvas-based applications, animations, interactive games, and rich user interfaces. React Konva is highly customizable and provides many features, such as shapes, animations, event handling, and filters. It is an open-source library and is widely used in web development projects.

Let's see how we implemented snapping shapes while dragging them in the canvas based on the position of other shapes in the canvas.

Setting up the canvas 🖼️

To begin, we will set up the canvas with a few shapes.

1import React, { useState } from "react";
2import { Stage, Layer, Rect, Circle } from "react-konva";
3
4const SHAPES = [
5  {
6    id: "1",
7    x: 0,
8    y: 0,
9    height: 100,
10    width: 100,
11    fill: "red",
12    shape: Rect,
13  },
14  {
15    id: "2",
16    x: 170,
17    y: 150,
18    height: 100,
19    width: 100,
20    fill: "blue",
21    shape: Rect,
22  },
23  {
24    id: "3",
25    x: 200,
26    y: 350,
27    height: 100,
28    width: 100,
29    fill: "black",
30    shape: Circle,
31  },
32  {
33    id: "4",
34    x: 450,
35    y: 250,
36    height: 100,
37    width: 100,
38    fill: "green",
39    shape: Circle,
40  },
41];
42
43export default function App() {
44  return (
45    <div style={{ width: window.innerWidth, height: window.innerHeight }}>
46      <Stage width={window.innerWidth} height={window.innerHeight}>
47        <Layer>
48          {SHAPES.map(({ shape: Shape, ...props }) => (
49            <Shape key={props.id} draggable name="shape" {...props} />
50          ))}
51        </Layer>
52      </Stage>
53    </div>
54  );
55}

The name prop is passed to all the Shapes in the canvas with a value of "shape". This helps us to query and find the shapes in the canvas that we need to use for snapping logic.

We have now set up a canvas with a few circles and squares that can be dragged. Link to Codesandbox.

Draggable canvas

Let’s add a Transformer 📐

In Konva, a Transformer is a node that allows a user to transform or manipulate a selected Konva shape on a canvas. It provides handles for rotating, scaling, and dragging the selected shape.

We add Transformer node to allow the user to apply transformations to the shapes in the canvas. Transformations like translation, scaling and rotations can be triggered on shapes through the provided handles. Also we would be listening to events from transformer nodes for implementing the snapping.

Transforms demo

Transformer can be imported from react-konva just like the other nodes. We can add a transformer to the canvas by adding it as a child to the Layer. Be sure to include a reference to both the Transformer and Stage so that we can access them later.

Let's also configure onMouseDown handler for shapes to select the shape and attach it to the transformer whenever we click on them. To unselect when clicking outside of a shape, add an onClick handler in Stage to remove the nodes from the Transformer by validating whether the event target is the Stage node.

1export default function App() {
2  const stageRef = useRef();
3  const transformerRef = useRef();
4  return (
5    <div style={{ width: window.innerWidth, height: window.innerHeight }}>
6      <Stage
7        onClick={e =>
8          e.target === stageRef.current && transformerRef.current.nodes([])
9        }
10        ref={stageRef}
11        width={window.innerWidth}
12        height={window.innerHeight}
13      >
14        <Layer>
15          {SHAPES.map(({ shape: Shape, ...props }) => (
16            <Shape
17              key={props.id}
18              draggable
19              name="shape"
20              onMouseDown={e => transformerRef.current.nodes([e.currentTarget])}
21              {...props}
22            />
23          ))}
24          <Transformer ref={transformerRef} />
25        </Layer>
26      </Stage>
27    </div>
28  );
29}

Implementing snapping 🪝

Now that we have set up the Transformer. Let's implement snapping. With that feature, when a shape is dragged near to another shape, the edges or the center of the dragged shape should automatically align with the edges or the center of the other shape in such a way that they are in the same line.

We will also show horizontal and vertical lines to visualize the snapping.

Snapping Demo

We will be using dragmove event in the Transformer node to implement snapping.

On dragmove event, we will find the possible snapping lines based on all the shapes on the canvas first.

To get all shapes on the canvas, we can use the find method on the Stage node. We will be using the name prop that we passed to all the shapes to query and get all the shapes in the canvas.

We don't want the selected shape to be considered for snapping. So we will be passing the selected shape as an argument excludedShape to the function.

The getClientRect method on the shape node returns the bounding box rectangle of a node irrespective of it's shape. We will be using that to find the edges and center of each shape.

1const getSnapLines = excludedShape => {
2  const stage = stageRef.current;
3  if (!stage) return;
4
5  const vertical = [];
6  const horizontal = [];
7
8  // We snap over edges and center of each object on the canvas
9  // We can query and get all the shapes by their name property `shape`.
10  stage.find(".shape").forEach(shape => {
11    // We don't want to snap to the selected shape, so we will be passing them as `excludedShape`
12    if (shape === excludedShape) return;
13
14    const box = shape.getClientRect({ relativeTo: stage });
15    vertical.push([box.x, box.x + box.width, box.x + box.width / 2]);
16    horizontal.push([box.y, box.y + box.height, box.y + box.height / 2]);
17  });
18
19  return {
20    vertical: vertical.flat(),
21    horizontal: horizontal.flat(),
22  };
23};

Then we find the snapping points for the selected shape.

The Transformer node creates a shape named back that covers the entire selected shape area. We will be using that to find the snapping edges of the selected shape.

Relative position of the back shape to the Stage node is the same as the selected shape. So we can use the getClientRect method on the back shape to get the bounding box of the selected shape.

1const getShapeSnappingEdges = () => {
2  const stage = stageRef.current;
3  const tr = transformerRef.current;
4
5  const box = tr.findOne(".back").getClientRect({ relativeTo: stage });
6  const absPos = tr.findOne(".back").absolutePosition();
7
8  return {
9    vertical: [
10      // Left vertical edge
11      {
12        guide: box.x,
13        offset: absPos.x - box.x,
14        snap: "start",
15      },
16      // Center vertical edge
17      {
18        guide: box.x + box.width / 2,
19        offset: absPos.x - box.x - box.width / 2,
20        snap: "center",
21      },
22      // Right vertical edge
23      {
24        guide: box.x + box.width,
25        offset: absPos.x - box.x - box.width,
26        snap: "end",
27      },
28    ],
29    horizontal: [
30      // Top horizontal edge
31      {
32        guide: box.y,
33        offset: absPos.y - box.y,
34        snap: "start",
35      },
36      // Center horizontal edge
37      {
38        guide: box.y + box.height / 2,
39        offset: absPos.y - box.y - box.height / 2,
40        snap: "center",
41      },
42      // Bottom horizontal edge
43      {
44        guide: box.y + box.height,
45        offset: absPos.y - box.y - box.height,
46        snap: "end",
47      },
48    ],
49  };
50};

From the possible snapping lines and the snapping edges of the selected shape, we will find the closest snapping lines.

We will define a SNAP_THRESHOLD to fix how close the shape should be to the snapping line to trigger a snap. Let's give it a value of 5 pixels. Based on the threshold, we will find the snap lines that can be considered for snapping.

Sorting the snap lines based on the distance between the line and the selected shape will give us the closest snapping lines as the first element in the array.

1const SNAP_THRESHOLD = 5;
2const getClosestSnapLines = (possibleSnapLines, shapeSnappingEdges) => {
3  const getAllSnapLines = direction => {
4    const result = [];
5    possibleSnapLines[direction].forEach(snapLine => {
6      shapeSnappingEdges[direction].forEach(snappingEdge => {
7        const diff = Math.abs(snapLine - snappingEdge.guide);
8        // If the distance between the line and the shape is less than the threshold, we will consider it a snapping point.
9        if (diff > SNAP_THRESHOLD) return;
10
11        const { snap, offset } = snappingEdge;
12        result.push({ snapLine, diff, snap, offset });
13      });
14    });
15    return result;
16  };
17
18  const resultV = getAllSnapLines("vertical");
19  const resultH = getAllSnapLines("horizontal");
20
21  const closestSnapLines = [];
22
23  const getSnapLine = ({ snapLine, offset, snap }, orientation) => {
24    return { snapLine, offset, orientation, snap };
25  };
26
27  // find closest vertical and horizontal snappping lines
28  const [minV] = resultV.sort((a, b) => a.diff - b.diff);
29  const [minH] = resultH.sort((a, b) => a.diff - b.diff);
30  if (minV) closestSnapLines.push(getSnapLine(minV, "V"));
31  if (minH) closestSnapLines.push(getSnapLine(minH, "H"));
32
33  return closestSnapLines;
34};

We need the closest snapping lines to be drawn on the canvas. We will be using Line node from react-konva for that. We can add a pair of states to store the coordinates of vertical and horizontal lines.

We will split the closest snapping lines into horizontal and vertical lines and set them in the corresponding states.

1const drawLines = (lines = []) => {
2  if (lines.length > 0) {
3    const lineStyle = {
4      stroke: "rgb(0, 161, 255)",
5      strokeWidth: 1,
6      name: "guid-line",
7      dash: [4, 6],
8    };
9    const hLines = [];
10    const vLines = [];
11    lines.forEach(l => {
12      if (l.orientation === "H") {
13        const line = {
14          points: [-6000, 0, 6000, 0],
15          x: 0,
16          y: l.snapLine,
17          ...lineStyle,
18        };
19        hLines.push(line);
20      } else if (l.orientation === "V") {
21        const line = {
22          points: [0, -6000, 0, 6000],
23          x: l.snapLine,
24          y: 0,
25          ...lineStyle,
26        };
27        vLines.push(line);
28      }
29    });
30
31    // Set state
32    setHLines(hLines);
33    setVLines(vLines);
34  }
35};

Let's combine all the above functions and create a onDragMove handler for the Transformer node.

We will be using the getNodes method on the Transformer node to get the selected shape.

Based on the selected shape and the canvas, we will find the closest snapping lines.

If there are no snapping lines within the SNAP_THRESHOLD, we will clear the lines from the canvas and return from the function.

Otherwise, we will draw the lines on the canvas and calculate the new position of the selected shape based on the closest snapping lines.

1const onDragMove = () => {
2  const target = transformerRef.current;
3  const [selectedNode] = target.getNodes();
4
5  if (!selectedNode) return;
6
7  const possibleSnappingLines = getSnapLines(selectedNode);
8  const selectedShapeSnappingEdges = getShapeSnappingEdges();
9
10  const closestSnapLines = getClosestSnapLines(
11    possibleSnappingLines,
12    selectedShapeSnappingEdges
13  );
14
15  // Do nothing if no snapping lines
16  if (closestSnapLines.length === 0) {
17    setHLines([]);
18    setVLines([]);
19
20    return;
21  }
22
23  // draw the lines
24  drawLines(closestSnapLines);
25
26  const orgAbsPos = target.absolutePosition();
27  const absPos = target.absolutePosition();
28
29  // Find new position
30  closestSnapLines.forEach(l => {
31    const position = l.snapLine + l.offset;
32    if (l.orientation === "V") {
33      absPos.x = position;
34    } else if (l.orientation === "H") {
35      absPos.y = position;
36    }
37  });
38
39  // calculate the difference between original and new position
40  const vecDiff = {
41    x: orgAbsPos.x - absPos.x,
42    y: orgAbsPos.y - absPos.y,
43  };
44
45  // apply the difference to the selected shape.
46  const nodeAbsPos = selectedNode.getAbsolutePosition();
47  const newPos = {
48    x: nodeAbsPos.x - vecDiff.x,
49    y: nodeAbsPos.y - vecDiff.y,
50  };
51
52  selectedNode.setAbsolutePosition(newPos);
53};

Finally, let's include the above functions inside the component and attach the onDragMove handler to Transformer.

1export default function App() {
2  const [hLines, setHLines] = useState([]);
3  const [vLines, setVLines] = useState([]);
4
5  const transformerRef = useRef();
6
7  // define onDragMove here
8
9  return (
10    <div style={{ width: window.innerWidth, height: window.innerHeight }}>
11      <Stage width={window.innerWidth} height={window.innerHeight}>
12        <Layer>
13          {SHAPES.map(({ shape: Shape, ...props }) => (
14            <Shape
15              onMouseDown={e => transformerRef.current.nodes([e.currentTarget])}
16              draggable
17              ref={props.shapeRef}
18              {...props}
19            />
20          ))}
21          <Transformer ref={transformerRef} onDragMove={onDragMove} />
22          {hLines.map((item, i) => (
23            <Line key={i} {...item} />
24          ))}
25          {vLines.map((item, i) => (
26            <Line key={i} {...item} />
27          ))}
28        </Layer>
29      </Stage>
30    </div>
31  );
32}

We have successfully implemented snapping functionality in the canvas, allowing the shapes to snap to a specific location while being dragged. You can now try moving the shapes near the edges and center of other shapes to see the snapping in action. Snapping Demo

All implementation details and live demo can be found in this CodeSandbox.

NeetoWireframe has not been launched for everyone yet. We are internally using it and are happy with how it’s shaping up. If you want to give it a try, then please send an email to [email protected].

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.