Move object within canvas boundary limit

前端 未结 6 1622
野性不改
野性不改 2020-12-08 00:58

I am trying to limit the moving object within the canvas but i am getting some difficulty to moving object with limit area on top and left side and when i scale the object w

6条回答
  •  一生所求
    2020-12-08 01:28

    I just Modified Balaji's code a little bit works better now

    canvas.on('object:moving', function (e) {
        var obj = e.target;
    
         // if object is too big ignore
        if(obj.getScaledHeight() > obj.canvas.height || obj.getScaledWidth() > 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);
        }});
    

提交回复
热议问题