Move object within canvas boundary limit

前端 未结 6 1609
野性不改
野性不改 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

    Just modified a bit too the code of Balaji and Surya T so it take care fully now of canvas zoom setting.

       _self.layer.on('object:moving', function (e) {
            var obj = e.target;
    
            obj.setCoords();
            var curZoom = obj.canvas.getZoom();
    
            //
            // if object is too big ignore
            if(obj.getScaledHeight() > obj.canvas.height || obj.getScaledWidth() > obj.canvas.width){
                return;
            }
    
            // top-left  corner
            if(obj.getBoundingRect().top < 0 || obj.getBoundingRect().left < 0){
                obj.top = Math.max(obj.top*curZoom, obj.top*curZoom-obj.getBoundingRect().top)/curZoom;
                obj.left = Math.max(obj.left*curZoom, obj.left*curZoom-obj.getBoundingRect().left)/curZoom;
            }
            // 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*curZoom, obj.canvas.height-obj.getBoundingRect().height+obj.top*curZoom-obj.getBoundingRect().top)/curZoom;
                obj.left = Math.min(obj.left*curZoom, obj.canvas.width-obj.getBoundingRect().width+obj.left*curZoom-obj.getBoundingRect().left)/curZoom;
            }
        });
    

提交回复
热议问题