Drag and drop inside of canvas

I am new to canvas and have built an app with rectangles. My goal is to use the mouse_up and mouse_down to drag these rectangles around. So far I have a function in_bubble(self, x, y, tup) that works and a mouse down

 def canvas_1_mouse_down (self, x, y, button, **event_args):
    # This method is called when a mouse button is pressed on this component
    x = int(x)
    y = int(y)
    coord = self.coord
    
    for elm in coord:
      loc = coord.index(elm)
      for elm in coord:
      if in_bubble(x, y, elm) is True:
        loc = coord.index(elm)
        coord.insert(loc, (x, y))

But I got to the point of realizing that this mouse_down is a one time function when clicked and how do I keep this process of updating the coordinate of my bubbles until the mouse is released. It is getting late and I thought I would send it out to you guys in hopes this would not keep me up. Any resources you can pass on to me in regards to canvas would be greatly appreciated. Hope you are having a lovely day.

Could you not just assume the mouse is still down unless you hear otherwise (via a mouse up event or the mouse coords move outside the confines of the canvas) ?

So, on mouse down event you set

self.dragging = True
self.element_im_moving = <whatever>

Then on the mouse move events you do

if self.dragging:
    # we are dragging - move self.element_im_dragging x/y accordingly

Then in mouse up event

if self.dragging:
    self.dragging = False
    # handle dropping

Here’s an absolutely dirt simple proof of concept :

https://anvil.works/ide#clone:7GHW5Q6W4AYX35SH=BQTJNV3KSFV5PSW65RB3NN6B

(edit - updated to allow clicking to create more boxes)

1 Like

Just out of curiosity - did you get this working ok?

Not yet. But not for a lack of resources. All aspects of life have really taken off this last week. I really appreciate your help and from looking at the code I think this approach will work well for what I am doing. I will let you know when it is up and running. Canvases are brand new to me and I am pretty excited for the world the open up.