Looking for working example, picture and selection related

I am looking for a code example.
How do I draw an area selection rectangle above an image without drawing it beyond the boundaries of the image itself, and by changing the size of the image (zoom)make the rectangle stay in the drawn position.
My code draw the image with the correct zoom related to the windows dimension inside a canvas area, draw the selection rectangle, but the selection is not limited to the image area and resizing the windows the selection do not move correctly in sync to the image

Any suggestions are welcome