from ipycanvas import Canvas, hold_canvas
canvas = Canvas(width=600, height=600)
canvas.fill_style = "#584f4e"
canvas.fill_rect(0, 0, 600, 600)
objects_to_draw = []
class Square_obj:
def __init__(self, x, y, width=100, height=40):
self.x = x
self.y = y
self.width = width
self.height = height
self.selected = False
objects_to_draw.append(self)
def set_x_y(self, x_in, y_in):
self.x = x_in
self.y = y_in
def draw(self):
canvas.fill_style = "#38a8a4"
canvas.fill_rect(
self.x - (self.width * 0.5), self.y - (self.height), self.width, self.height
)
if self.selected:
canvas.fill_style = "#9dcea6"
else:
canvas.fill_style = "#dee7bc"
canvas.fill_rect(
self.x - (self.width * 0.5),
self.y - (self.height * 0.5),
self.width,
self.height,
)
def is_selected(self, x_in, y_in):
x_coord = self.x - (self.width * 0.5)
y_coord = self.y - (self.height * 0.5)
if (
x_in > x_coord
and x_in < (x_coord + self.width)
and y_in > y_coord
and y_in < (y_coord + self.height)
):
self.set_selected(True)
return True
else:
self.set_selected(False)
return False
def set_selected(self, state):
self.selected = state
def canvas_restart():
canvas.clear()
canvas.fill_style = "#584f4e"
canvas.fill_rect(0, 0, 600, 600)
def handle_mouse_down(x, y):
if [o for o in objects_to_draw if o.selected]:
[o.set_selected(False) for o in objects_to_draw if o.selected]
return False
check_bool_pos = list(
set([check_region.is_selected(x, y) for check_region in objects_to_draw])
)
if len(check_bool_pos) == 1:
if check_bool_pos[0] == False:
s = Square_obj(x, y)
s.set_selected(False)
s.draw()
else:
canvas_restart()
[o.draw() for o in objects_to_draw]
if len(check_bool_pos) == 0:
s = Square_obj(x, y)
s.set_selected(False)
s.draw()
def handle_mouse_move(x, y):
if [o for o in objects_to_draw if o.selected]:
with hold_canvas():
[o for o in objects_to_draw if o.selected][-1].set_x_y(x, y)
canvas_restart()
[o.draw() for o in objects_to_draw]
canvas.on_mouse_down(handle_mouse_down)
canvas.on_mouse_move(handle_mouse_move)
canvas