JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="fabriccanvas" width="800" height="500" style="border:1px solid #ccc"></canvas>
JavaScript
window.canvas = new fabric.Canvas('fabriccanvas');
window.counter = 0;
newleft = 0;
canvas.selection = false;
plusrect();
plusrect();
plusrect();
function plusrect(top, left, width, height, fill) {
window.canvas.add(new fabric.Rect({
top: 300,
name: 'rectangle ' + window.counter,
left: 0 + newleft,
width: 100,
height: 100,
fill: 'rgba(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ', 0.75)',
originX: 'left',
originY: 'top',
cornerSize: 15,
perPixelTargetFind: true,
minScaleLimit: 1,
maxHeight: document.getElementById("fabriccanvas").height,
maxWidth: document.getElementById("fabriccanvas").width,
}));
window.counter++;
newleft += 200;
}
//handle moving object
this.canvas.on('object:moving', function(event) {
var obj = event.target;
intersectingCheck(obj);
});
function intersectingCheck(activeObject) {
activeObject.setCoords();
if(typeof activeObject.refreshLast != 'boolean') {
activeObject.refreshLast = true
};
//loop canvas objects
activeObject.canvas.forEachObject(function (targ) {
if (targ === activeObject) return; //bypass self
//check intersections with every object in canvas
if (activeObject.intersectsWithObject(targ)
|| activeObject.isContainedWithinObject(targ)
|| targ.isContainedWithinObject(activeObject)) {
//objects are intersecting - deny saving last non-intersection position and break loop
if(typeof activeObject.lastLeft == 'number') {
activeObject.left = activeObject.lastLeft;
activeObject.top = activeObject.lastTop;
activeObject.refreshLast = false;
return;
}
}
else {
...