在画布边界限制内移动对象 [英] Move object within canvas boundary limit

查看:33
本文介绍了在画布边界限制内移动对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试限制画布内的移动对象,但是在顶部和左侧的限制区域中移动对象时遇到了一些困难,当我将对象缩放得更大时,我也无法限制移动画布左侧和顶部的对象

I am trying to limit the moving object within the canvas but i am getting some difficulty in moving the object in the limit area on top and left side and when i scale the object bigger then also i am not able to limit the moving object on left and top sides of the canvas

canvas.observe("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;
  }

  var halfw = obj.currentWidth/2;
  var halfh = obj.currentHeight/2;
  var bounds = {
    tl: {x: halfw, y:halfh},
    br: {x: obj.canvas.width-halfw, y: obj.canvas.height-halfh}
  };

  // top-left  corner
  if(obj.top < bounds.tl.y || obj.left < bounds.tl.x) {
    obj.top = Math.max(obj.top, bounds.tl.y);
    obj.left = Math.max(obj.left, bounds.tl.x )
  }
        
  // bot-right corner
  if(obj.top > bounds.br.y || obj.left > bounds.br.x) {
    obj.top = Math.min(obj.top, bounds.br.y);
    obj.left = Math.min(obj.left, bounds.br.x)
  }
});

推荐答案

只需将以下代码添加到您的 js 文件中,并根据画布的高度和宽度更改 scale X(left) 和 Y(top) 的值.

Just add the below code in your js file and change the value of scale X(left) and Y(top) according to your canvas height and width.

// canvas moving limit 

canvas.observe("object:moving", function(e){
      var obj = e.target;
         // if object is too big ignore

        var halfw = obj.currentWidth/2;
        var halfh = obj.currentHeight/2;
        var bounds = {tl: {x: halfw, y:halfh},
            br: {x: obj.canvas.width , y: obj.canvas.height }
        };

        // top-left  corner



            // alert("text");
        if(obj.top < bounds.tl.y || obj.left < bounds.tl.x){
            obj.top = Math.max(obj.top, '10'  );
            obj.left = Math.max(obj.left , '50' ) 
        }


        // bot-right corner
        if(obj.top > bounds.br.y || obj.left > bounds.br.x ){
            obj.top = Math.min(obj.top, '360'  );  
            obj.left = Math.min(obj.left, '470' )  
        }

});
// end canvas moving limit

这篇关于在画布边界限制内移动对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆