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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With