JSFiddle - React, Tailwind, and code Playground

by prabhath

HTML

<canvas id="canvas" width="500" height="400" />

JavaScript

canvas = new fabric.Canvas("canvas");

// create your "bounding box"
boundingBox = new fabric.Rect({
    id: 'bounding-box',
    width: 499,
    height: 399,
    hasBorders: false,
    hasControls: false,
    lockMovementX: true,
    lockMovementY: true,
    evented: false,
    stroke: "black",
    fill: "white",
    selectable: false
});
this.canvas.add(boundingBox);

// Create default object
object = new fabric.Rect({
    top: 50,
    left: 50,
    width: 50,
    height: 50
});
this.canvas.add(object);

// Event on object moving
canvas.on("object:moving", function(e) {
    var object = e.target;
    
    // check left
    if (object.left < boundingBox.left) {
        object.set('left', boundingBox.left);
    }
    // check right
    else if (object.left + object.width > boundingBox.left + boundingBox.width) {
        object.set('left', boundingBox.left + boundingBox.width - object.width);
    }
    // check top
    if (object.top < boundingBox.top) {
        object.set('top', boundingBox.top);
    }
    // check bottom
    else if (object.top + object.height > boundingBox.top + boundingBox.height) {
        object.set('top', boundingBox.top + boundingBox.height - object.height);
    }
    console.log(canvas.toJSON());
});