Snapping object to grid
HTML
<script src="https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c" width="600" height="600"></canvas>
CSS
canvas {
border: 1px solid #ccc;
}
JavaScript
var canvas = new fabric.Canvas('c', { selection: false });
var grid = 10;
// create grid
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 }))
}
// add objects
canvas.add(new fabric.Rect({
left: 100,
top: 100,
width: 50,
height: 50,
fill: '#faa',
originX: 'left',
originY: 'top',
centeredRotation: true
}));
canvas.add(new fabric.Circle({
left: 300,
top: 300,
radius: 50,
fill: '#9f9',
originX: 'left',
originY: 'top',
centeredRotation: true
}));
// snap to grid
/*
canvas.on('object:moving', function(options) {
options.target.set({
left: Math.round(options.target.left / grid) * grid,
top: Math.round(options.target.top / grid) * grid
});
});
*/
canvas.on('object:scaling', function(options) {
var target = options.target;
console.log(options);
console.error(target.width);
var w = target.width * target.scaleX,
h = target.height * target.scaleY,
snap = { // Closest snapping points
top: Math.round(target.top / grid) * grid,
left: Math.round(target.left / grid) * grid,
bottom: Math.round((target.top + h) / grid) * grid,
right: Math.round((target.left + w) / grid) * grid
},
threshold = grid,
dist = { // Distance from snapping points
top: Math.abs(snap.top - target.top),
left: Math.abs(snap.left - target.left),
bottom: Math.abs(snap.bottom - target.top - h),
right: Math.abs(snap.right - target.left - w)
},
attrs = {
scaleX: target.scaleX,
scaleY: target.scaleY,
top: target.top,
left: target.left
};
switch (target.__corner) {
case 'tl':
if (dist.left < dist.top && dist.left < threshold) {
attrs.scaleX = (w - (snap.left -...