Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
111
rated 0 times [  116] [ 5]  / answers: 1 / hits: 23276  / 10 Years ago, mon, april 7, 2014, 12:00:00

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)
}
});

More From » canvas

 Answers
59

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

[#71578] Friday, April 4, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
neildrews

Total Points: 166
Total Questions: 103
Total Answers: 85

Location: Moldova
Member since Sat, Aug 6, 2022
2 Years ago
neildrews questions
Fri, Feb 18, 22, 00:00, 2 Years ago
Tue, Oct 12, 21, 00:00, 3 Years ago
Tue, Mar 23, 21, 00:00, 3 Years ago
Sun, Aug 16, 20, 00:00, 4 Years ago
;