Draw shapes on top of an image?

Hi, I would like to be able to draw shapes on top of an image. I would store the shapes separately from the image, so must be able to relate the coordinates to the coordinates in the image. Is there a way to achieve this?

It does not seem possible to add an image as background to canvas.

Look at something like PIL :

A simple example :

And whilst not directly related to what you’re trying to do, here’s PIL being used in Anvil to generate images :

1 Like

Hi Stein,

Did you get anywhere using PIL? Need any more tips?

Hi David, thanks! I’ve checked out your links and it seems I will get what I need from PIL.

Hi Shaun, thanks for asking and offering your help. It seems I get what I need from PIL. On vacation, so haven’t tested out properly yet.

Hi,
If I may add my few cents to it…you can use javascript to draw an image in the context and then draw any shape on the image from python functions e.g:
Note: I am not using custom html, hence finding elements by tag name etc.

In your html code

<script>
function myCanvas() {
    var c = document.getElementsByTagName("canvas")[0];//find canvas
    var ctx = c.getContext("2d");
    var img = document.getElementsByTagName("img")[2];//find image loaded from file loader
    var imageObj = new Image();
    imageObj.onload = function(){
    ctx.drawImage(img,0,0);
    };
    imageObj.src = img.src;
}

My Form1 function:

def file_loader_1_change(self, file, **event_args):
    """This method is called when a new file is loaded into this FileLoader"""
    small_img = anvil.image.generate_thumbnail(file, 640) #reducing image size
    self.image_1_show(small_img,**event_args)
    width, height = anvil.image.get_dimensions(small_img)
   #setting canvas size to my small_img size
    self.canvas_1.width = width
    self.canvas_1.height = height

Image is now displayed:

def image_1_show(self,file,**event_args):
    """This method is called when the Image is shown on the screen"""
    self.image_1.source = file

Call js when Image is clicked:

def image_1_mouse_down(self, x, y, button, **event_args):
    """This method is called when a mouse button is pressed on this component"""
    self.call_js('myCanvas')

Now, any kind of canvas drawing method ,like:

def canvas_1_mouse_down(self, x, y, button, **event_args):
    """This method is called when a mouse button is pressed on this component"""
    self.canvas_1.stroke_rect(x,y,50,50)
    pass

You’ll need to convert coord system on images to match x and y values,

Hope this is of any help,

Archie

1 Like