JSFiddle - React, Tailwind, and code Playground
by cyberpantz
HTML
<script src="http:////ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="controls">
<button id="btn_group" class="group">Group</button>
<button id="btn_ungroup" class="ungroup">Ungroup</button>
</div>
<canvas id="c" width="500" height="500"></canvas>
</body>
</html>
CSS
.controls{padding:5px}
.controls *{display:none;}
JavaScript
var cvs = new fabric.Canvas("c"),
items = [],
margin = 20,
w = 30,
h = 70,
x = margin + w / 2,
y = margin + h / 2;
// build grid
for (var i = 0, n = 15; i < n; i++) {
if (i >= 1 && (i + 1) % 5 === 1) { y += h + 1; x = margin + w / 2; }
var rect = new fabric.Rect({ fill: "#CCCCCC", width: w, height: h, left: x,top: y });
rect.set({
'lockScalingX': true,
'lockScalingY': true
});
x += w + 1;
cvs.add(rect);
}
// bind events
/**
* triggered when a selection is made by dragging a box around elements
*/
cvs.observe('selection:created', function(e) {
var grp = cvs.getActiveGroup();
if (grp) {
// prevent scaling
grp.set({
'lockScalingX': true,
'lockScalingY': true
});
$(".controls .group").show();
$(".controls .ungroup").hide();
}
});
cvs.observe('selection:cleared', function(e) {
$(".controls .group").hide();
$(".controls .ungroup").hide();
});
/**
* triggered when an object is selected
*/
cvs.observe('object:selected', function(e) {
var obj = cvs.getActiveObject();
if (obj === cvs.getActiveGroup()) {
return;
}
if (obj && obj.type == "group") {
$(".controls .ungroup").show();
$(".controls .group").hide();
} else {
$(".controls .ungroup").hide();
$(".controls .group").hide();
}
});
// my troubles lie within this method...
cvs.observe('object:moving', function(e) {
var targ = e.target;
// filter out itself
var items = cvs.getObjects().filter(function(o){
return targ !== o;
});
var hit = false;
for (var i = 0, n = items.length; i < n; i++) {
var m = items[i];
if (targ.type == "group") {
if (targ.intersectsWithObject(m)) {
targ.setFill("red");
hit = true;
console.log("GROUP HIT");
} else {
if (!hit) {
...