Our current image position is at the green circle at the center and we need it to be the top left corner of the canvas(the black & white circle). So we need to push back(subtract) half of canvas's width/height inorder to reach the black & white circle. And then you can add the x,y coordinate you need and continue to get the image position you need.
And why do we need to push back to the top left corner? Because e.x
and e.y
starts from top left corner. It is rather easy(IMO) to find the image coordinate at the top left corner of the canvas, than to make e.x
and e.y
work with the image coordinate at the center.
CodePudding user response:
Note that (event.x, event.y)
is the screen coordinates relative to the top-left corner of the canvas. To get the real canvas coordinates, you can use canvas.canvasx()
and canvas.canvasy()
:
# get the real coordinates in the canvas
# note that canvasx() and canvasy() return float number
x, y = int(canvas.canvasx(event.x)), (canvas.canvasy(event.y))
So if the top-left corner of the image is at (img_x, img_y)
inside the canvas, then the coordinates in the image will be (x-img_x, y-img_y)
.
To apply on your posted code:
def get_mouse_posn(event):
global topx, topy
topx, topy = int(canvas.canvasx(event.x)), int(canvas.canvasy(event.y))
def update_sel_rect(event):
global botx, boty
botx, boty = int(canvas.canvasx(event.x)), int(canvas.canvasy(event.y))
canvas.coords(rect_id, topx, topy, botx, boty)
To get the selected region in the image:
def get_selected_region():
global topx, topy, botx, boty
# make sure topx < botx and topy < boty
topx, botx = min(topx, botx), max(topx, botx)
topy, boty = min(topy, boty), max(topy, boty)
# top-left corner of image is at (img_x, img_y) inside canvas
region = (topx-img_x, topy-img_y, botx-img_x, boty-img_y)
return region