# Center of Image whose height, width and position are known

I have been struggling to find the center of an image(rectangle). I have following data with me:

width: w,
height: h,
position: (x,y)


My image is an object on canvas. I am using KonvaJS framework. My concern is not specific to image it's with Rect, Square as well but cause images are actually rectangle or squares and I believe that solution will be common for all. What I want to do is I need to find the center of the shape so that I can perform the desired operation. eg. I want to place the connector between a circle and image. End point of the connectors should be at the center like the way I have displayed it in image. Please let me know what should I do to achieve this. I believe it will be done by Math.atan() and Math.atan2() but don't know how can I use them. I am new to this bizarre.

• What about (X+w/2, y+h/2)? – ElDuderino Aug 17 '16 at 11:27
• Are you struggling with the maths or with the code? – Alexandre Vaillancourt Aug 17 '16 at 11:28

If the (X,Y) is at the top-left corner of the rectangle as you have drawn in the picture in your question, then the center is simply:

(X + W*0.5 , Y - H*0.5 )


Note that it is always a good practice to multiply by 0.5 instead of dividing by 2, since multiplications are much less computationaly expensive than divisions.

• I think it should not be simply like this. What I want to achieve it something like this gamedev.stackexchange.com/questions/14602/… so that I need not be worried about whether x and y are negative or positive. – Hitesh Kumar Aug 17 '16 at 11:34
• @Hitesh Kumar Do you mean that the rectangles can be rotated? – MAnd Aug 17 '16 at 11:38
• @HiteshKumar It does not matter if X or Y are positive or negative, nor if the rectangle can be dragged. If the rectangle does not rotate (and if X,Y is in the top-left), then the rectangle's center will always be given by that simple formula. If the rectangle can rotate, then you will need the diagonal through some trigonometry – MAnd Aug 17 '16 at 11:47
• "Note that it is always a good practice to multiply by 0.5 instead of dividing by 2, since multiplications are much less computationaly expensive than divisions." That's premature optimization. :) – Alexandre Vaillancourt Aug 17 '16 at 11:52
• @HiteshKumar Seeing the amount of requests that you have, it's probably because your question is unclear. Please edit it and improve it. – Alexandre Vaillancourt Aug 17 '16 at 11:53

width: w, height: h, position: (x,y), centre: (x + w/2, y + h/2) 

Hope it helps.