Search code examples
javascripthtmlbuttoncanvasbounding-box

How can I add a button on top of an image at a specific (bounding-box) position without using canvas?


I am trying to add button(s) on top of an image. From my backend I will be given a bounding-box (x, y, image_width, image_height), which I want to use to place the button at the bounding-box position.

My first try was to use canvas -> draw a rectangle and then add an event listener to get the button. But this method is in my opinion not very clean.

Is there any other way to achieve this without using canvas.

....
ctx.fillStyle = "red";
ctx.drawImage(img,0,0); 
ctx.fillRect(x, y, width, height);
canvas.addEventListener('click', function(evt) {
.... 

Here's a fiddle which should show my current result jsfiddle

Edit: Just a small edit, the button position is not constant, it depends on the bounding-box I will be given. It's also not a static image but a livestream, although the image size (640x480) is constant.

Solution jsfiddle


Solution

  • Why does your backend need to set the button position? This seems un-ideal, but perhaps there's a good reason for it. Will the backend provide coordinates relative to the whole document, or a single element? Does the button need to move over time?

    My instinct is to add a div, set your image as the div's background, and then place the button in the div at the correct spot. Are you working in vanilla JS or a framework like React? This will affect how you'd place the button.