Search code examples
interactjs

Snapping (resizable) items to grid with interact.js


I'm trying to get my resizable items to snap to a grid (using InteractJS). I have defined the draggable config as follows:

draggable = {
    modifiers: interact.modifiers.snap({
        targets: [interact.snappers.grid({ x: 5, y: 5 })],
        range: Infinity,
        relativePoints: [
          { x: 0, y: 0 },
        ],
    })
}

The items snap to the grid just fine, but I'm seeing some weird behavior. My items top left corner is placed at 0,0. Then if I drag the item along the y-axis, the initial jump goes to 0,1, then it follows the grid correctly afterwards 0,6, 0,11 etc.

Same with the x-axis, if the item is at 0,0 and gets dragged to the right the initial jump is 3px, so to 3,0 and then afterwards the grid is followed; 8,0, 13,0 etc

How do I set the corner point of the grid to be at 0,0? It seems the grid is slightly misaligned from the div the items reside in. Note that I do want to be able to drag items outside their container div, but I want 0,0 to be a snappable position and not 3,1.


Solution

  • Got it working with the following config:

    draggableModifiers.push(
          interact.modifiers.snap({
            targets: [interact.snappers.grid({ x: 5, y: 5 })],
            range: Infinity,
            relativePoints: [
              { x: 0, y: 0 }, // snap relative to the element's top-left
            ],
            offset: "self", // adding this fixed the misalignment issue
          })
        );