'On the fabricjs how can you determine if an object already exists at certain coordinates?
I have been working with fabricjs for the last few weeks and I cannot find a solution for an issue I am having. I have an object and I would like to programmatically determine if the area around it is "empty" (there are no objects ), so if I would add an object there they would not intersect.
I have been playing around with canvas.findTarget and different "virtual" objects but I cannot get anything to work.
This is a solution I found:
var targetPoint = new fabric.Point(target.left + offset + 1, target.top + 1);
if (obj.containsPoint(targetPoint)) {
objectOnRight = obj;
}
Best regards, Alex
Solution 1:[1]
This should get you fairly close (some code I've used, in the past, to display a context menu):
fabric.util.addListener(document.getElementsByClassName('upper-canvas')[0], 'contextmenu', function (env) {
var x = env.offsetX;
var y = env.offsetY;
var itemIndex = -1;
$.each(canvas.getObjects(), function (i, e) {
// e.left and e.top are the middle of the object use some "math" to find the outer edges
if (e.selectable && e.id != 'canvasNumbers') {
var d = e.width * e.scaleX / 2;
var h = e.height * e.scaleY / 2;
if (x >= (e.left - d) && x <= (e.left + d)) {
if (y >= (e.top - h) && y <= (e.top + h)) {
itemIndex = i;
}
}
}
});
if (itemIndex > -1) {
canvas.setActiveObject(canvas.getObjects()[itemIndex]);
canvasSelectedItem = canvas.getObjects()[itemIndex];
$('.contextmenu').css({
top: env.pageY + 'px',
left: env.pageX + 'px'
}).show();
}
env.preventDefault();
return false; //stops the event propigation
});
Let me know if you have any further questions. Happy to help more!
Solution 2:[2]
I have an idea of using two events here to catch when mouse is over a given object and when out:
myobject[i].on('mouseover', () => {
console.log("mouse over"+i)
});
myobject[i].on('mouseout', () => {
console.log("mouse out"+i)
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tim Harker |
Solution 2 | Marcin ?migrodzki |