Issue with object while restricting it to canvas b

2020-07-26 11:14发布

问题:

I am currently running with my project and in that i have used fabric js to work with canvas. In that i want my canvas object not to go out of canvas boundary.I did this code and it is working fine unless and until i am rotating it. but when i am rotating the object, top left of that object is getting as per rotation and my code is not working well. I want some solution which will work in any condition but my object should not go outside of canvas boundary. Thanks

var canvas=new fabric.Canvas('demo');
canvas.on('object:moving',function(e){
    if(e.target.getWidth()+e.target.left>canvas.width)
    {
        e.target.set('left',canvas.width-e.target.getWidth());
        e.target.setCoords();
        canvas.renderAll();
    }
    if(e.target.getHeight()+e.target.top>canvas.height)
    {
        e.target.set('top',canvas.height-e.target.getHeight());
        e.target.setCoords();
        canvas.renderAll();
    }
    if(e.target.top<0)
    {
        e.target.set('top',0);
        e.target.setCoords();
        canvas.renderAll();
    }
    if(e.target.left<0)
    {
        e.target.set('left',0);
        e.target.setCoords();
        canvas.renderAll();
    }
});
var text=new fabric.IText('Jayesh');
canvas.add(text);
<script src="http://fabricjs.com/lib/fabric.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<canvas id="demo" style="width:100px;height:100px;border: 1px solid black"></canvas>

回答1:

Please try this.

http://jsfiddle.net/gaz704v7/

    var canvas=new fabric.Canvas('demo');
    canvas.on('object:moving', function (e) {
        var obj = e.target;
        // if object is too big ignore
        if(obj.currentHeight > obj.canvas.height || obj.currentWidth > obj.canvas.width) {
            return;
        }
        obj.setCoords();
        // top-left  corner
        if(obj.getBoundingRect().top < 0 || obj.getBoundingRect().left < 0) {
            obj.top = Math.max(obj.top, obj.top-obj.getBoundingRect().top);
            obj.left = Math.max(obj.left, obj.left-obj.getBoundingRect().left);
        }
        // bot-right corner
        if(obj.getBoundingRect().top+obj.getBoundingRect().height  > obj.canvas.height || obj.getBoundingRect().left+obj.getBoundingRect().width  > obj.canvas.width) {
            obj.top = Math.min(obj.top, obj.canvas.height-obj.getBoundingRect().height+obj.top-obj.getBoundingRect().top);
            obj.left = Math.min(obj.left, obj.canvas.width-obj.getBoundingRect().width+obj.left-obj.getBoundingRect().left);
        }
    });
    var text=new fabric.IText('Jayesh');
    canvas.add(text);