I have two boxes positioned on a canvas that I am trying to center. You can view this on JS fiddle: http://jsfiddle.net/FVU47/5/
My canvas has 1000 height and 1000 width as follows:
I am then attempting to center the two boxes with the following code, which would place either box1 or box2 in the center of the canvas, depending on whether I click on "Go to Box 1" or "Go to Box 2" (see the bottom of the JSFiddle Result quadrant:
$(document).ready(function(){
$("#box1click").click(function(){
if (rect1.x <= 500) {
positionWidthSet = Math.abs(rect1.x - canvas.width/2) + rect1.x;
}
else{
positionWidthSet = Math.abs(Math.abs(rect1.x - canvas.width/2) + rect1.x)
}
if (rect1.y >= 500) {
positionHeightSet = Math.abs(rect1.y -canvas.height/2);
}
else{
positionHeightSet = Math.abs(Math.abs(rect1.y - canvas.height/2) + rect1.y);
}
positionCanvasContext(positionWidthSet,positionHeightSet);
});
});
$(document).ready(function(){
$("#box2click").click(function(){
if (rect2.x <= 500) {
positionWidthSet = Math.abs(rect2.x - canvas.width/2) + rect2.x;
}
else{
positionWidthSet = Math.abs(Math.abs(rect2.x - canvas.width/2) + rect2.x)
}
if (rect2.y >= 500) {
positionHeightSet = Math.abs(rect2.y -canvas.height/2);
}
else{
positionHeightSet = Math.abs(Math.abs(rect2.y - canvas.height/2) + rect2.y);
}
positionCanvasContext(positionWidthSet,positionHeightSet);
});
});
Currently, clicking on either "Go to Box 1" or "Go to Box 2" does not center the canvas around either Box 1 or Box 2, even though experimenting with my formulas in the console would seem to indicate otherwise.