The intersectsWithObject() method in Fabric.js checks whether one graphical object overlaps with another on the canvas. This functionality supports features like collision prevention and automatic alignmnet in interactive applications.
In a practical example, create a canvas and add multiple shapes—such as rectangles, circles, and triangles. Attach an event listener to the object:moving event to monitor shape movements. During movement, iterate over all canvas objects using forEachObject(), excluding the currently dragged item. For each other object, call intersectsWithObject() on the moving target; if it returns true, log the type of the intersected object to the console.
<canvas id="canvas" width="500" height="500" style="border: 1px solid #ccc;"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.0/fabric.min.js"></script>
<script>
const canvas = new fabric.Canvas('canvas');
const rectangle = new fabric.Rect({
left: 260,
top: 110,
width: 80,
height: 60,
fill: 'hotpink'
});
const circle = new fabric.Circle({
top: 200,
left: 150,
radius: 30,
fill: 'yellowgreen'
});
const triangle = new fabric.Triangle({
width: 100,
height: 100,
left: 300,
top: 200,
fill: 'skyblue'
});
canvas.add(rectangle, circle, triangle);
canvas.on('object:moving', (event) => {
canvas.forEachObject((obj) => {
if (obj === event.target) return;
if (event.target.intersectsWithObject(obj)) {
console.log(`Intersected with: ${obj.type}`);
}
});
});
</script>
The method accepts three parameters: other (the object to test against), absoluteopt (a boolean to use coordinates without viewport transformation), and calculateopt (a boolean to use current position coordinates).