Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

javascript - Move object within canvas boundary limit

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)
  }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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);
  }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...