Make canvas change size according to image

What I’m trying to do:
I want to input a image url and make a URLMedia, get width and height of image, show it on canvas and adjust canvas size according to the size of image.

What I’ve tried and what’s not working:
I tried to get width and height of image using anvil.image.get_dimensions(), and it works. When I set the width and height to canvas, sometimes it changed to the size I want, but sometimes it didn’t.
I tried these two images(first one works, but the second one doesn’t):
image1
image2

Clone link:
https://anvil.works/build#clone:IHSRRY3OYHCZZ34D=TNNG5CEZ4AHXHZOKHUF632FA

Did you read this section of the canvas docs? Anvil Docs | Canvas

There’s a canvas method you’re supposed to call after resizing the canvas.

1 Like

Thansk for the reply. I used reset_context() after reset width and height. I think it makes it better but when using image2 it is still not showing the whole image.
I am not sure if I did it wrong or image2 is just too big.

def button_1_click(self, **event_args):
        """This method is called when the button is clicked"""
        self.canvas_1.clear_rect(0, 0, self.canvas_1.width, self.canvas_1.height)
        media = URLMedia(self.text_box_1.text)
        width, height = anvil.image.get_dimensions(media)
        self.text_box_1.text = f"width:{width}, height:{height}"
        self.canvas_1.width = width
        self.canvas_1.height = height
        self.canvas_1.reset_context()
        self.canvas_1.draw_image(media)

By default, Anvil lays out components with margins left and right based on how wide the window is. If you go to the Containers Properties section of your canvas component, and click on full_width_row, the canvas will stretch wider than it would otherwise. There’ll still be a maximum based on how wide your window is (that second image I can see all of only if I stretch the window across two monitors).

If you want to display images that might be bigger than the available space, you need to define what you want to have happen. Does the image get scaled down to the available space? Do scroll bars appear? Both of those need different sorts of solutions.

For what it’s worth (no relation to your current issue), you should clear the canvas after setting the size and calling reset_context.

1 Like

oh!!! full_width_row is what I need! Thanks for the answer.