title: Canvas: Rectangles -- Snap to grid / Snap to objects
body: <p>I managed to manipulate Fabric.js to add a snap and scale to grid functionality by:</p>
  
  <pre><code>var grid = 100;
  //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) {
      options.target.set({
          left: Math.round(options.target.left / grid) * grid,
          top: Math.round(options.target.top / grid) * grid
      });
  });
  </code></pre>
  
  <p>Now I want to add snap to objects functionality. My idea was to check intersection of two objects and then lock somehow the movement. I know its not the best attempt, but at least it snaps to it, but does not allow to move the object away anymore. And: right now it is not implemented well. See: <a href="http://jsfiddle.net/gcollect/y9kyq/" rel="noreferrer">http://jsfiddle.net/gcollect/y9kyq/</a></p>
  
  <p>I have three issues:</p>
  
  <ol>
  <li>The "snap" doesn't work well, because the object left attribute depends on the pointer somehow. Replication by dragging object and watching my controls output. For example when moving the red rectangle to position left:62, the rectangle isn't intersected with the blue rectangle and can still moved away. How can I reload the actual left value of the rectangle. Because of my snap to grid lines, it is at left:100 and not at left:62.</li>
  <li>Any idea how I can add a snap to object functionality? And prohibit intersection?</li>
  <li>How can I check this for n objects and not only for two?</li>
  </ol>
  
  <p>Thanks for your comments.</p>
  
  <p>PS:
  The jsfiddle example doesn't show the scale to grid functionality, because it needed Fabric.js manipulation in line: 11100 </p>
  
  <pre><code>var distroundedforgrid = Math.round(dist/100)*100;      
        transform.newScaleX = Math.round((transform.original.scaleX * distroundedforgrid / lastDist)*10)/10;
        transform.newScaleY = Math.round((transform.original.scaleY * distroundedforgrid / lastDist)*10)/10;
  
        target.set('scaleX', transform.newScaleX);
        target.set('scaleY', transform.newScaleY);
      }
  </code></pre>