Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FabricJS Fluid snap to grid

I'd like to use this http://jsfiddle.net/fabricjs/S9sLu/ function where objects can be snapped to grid, the problem is that I don't want it to snap directly to the lines but when it is getting close to it only. so the movements of objects are fluid and it can be snapped if the user wants to.

Here is the javascript, I think it has to do with Math.round() :

grid = 50;

// Grid display part
for (var i = 0; i < (600 / grid); i++) {
  canvas.add(new fabric.Line([ i * grid, 0, i * grid, 600], { stroke: '#ccc', selectable: false }));
  canvas.add(new fabric.Line([ 0, i * grid, 600, i * grid], { stroke: '#ccc', selectable: false }))
}

// Snapping part
canvas.on('object:moving', function(options) { 
  options.target.set({
    left: Math.round(options.target.left / 50) * 50,
    top: Math.round(options.target.top / 50) * 50
  });
});

any suggestion on how I can accomplish that ?

like image 607
Hiroyuki Nuri Avatar asked Mar 22 '17 17:03

Hiroyuki Nuri


1 Answers

If I understood you correctly, this small tweak should take care of it:

canvas.on('object:moving', function(options) {
  if (Math.round(options.target.left / grid * 4) % 4 == 0 &&
    Math.round(options.target.top / grid * 4) % 4 == 0) {
    options.target.set({
      left: Math.round(options.target.left / grid) * grid,
      top: Math.round(options.target.top / grid) * grid
    }).setCoords();
  }
});

(or get you going in the right direction, smooth and snaps-to on mouse up)

Here's the updated Plunker, https://jsfiddle.net/rekrah/q0xe7yfz/.

Let me know if you need any further help.

like image 78
Tim Harker Avatar answered Sep 18 '22 20:09

Tim Harker