0

I'm new to canvas and I don't really know how to go about it. What I want to do is to create a canvas where there is an image that loads and be able to draw rectangles and save those coordinates of each rectangle in some array and then save it in bbdd. The idea would be more or less like this, as I show in the image. You could select one of the rectangles and erase it, in case I have made a mistake when drawing over it?

I would appreciate some ideas of how to do it.

enter image description here

This is an example video

Alexd2
  • 1,044
  • 2
  • 15
  • 28

1 Answers1

0

Since you need to add click events on individual rectangles, it'll be easier if you use div-containers instead of canvas to draw the boxes.

Set the image position as absolute (at top left position) and iterate through all the boxes to show the rectangle.

<div class="image-app-container" style="position: relative">
  <img src="..." style="position: absolute; top: 0, left: 0">

  // Iterate through the all the boxes, I'm using react JSX code here
  {boxes.map(box => {
     return <div 
       style={{"position": "absolute", "top": box.top, "left": box.left, "border": "2px solid darkred"}}
       onClick= {this.selectBox} //selectBox function saves the clicked box info
       />
   })  
  }

</div>

Once you've selected the rectangle, you can update/delete its size or position.

To add new boxes, add a click handler on the container-div

var c = document.querySelector('.image-app-container');
var handleClick =  (e) => {
  // Calculate position coordinates using e.clientX &  e.clientY values
  // Add the box with positions to your current list
}
c && c.addEventListener('click', handleClick)
ankur1812
  • 97
  • 4
  • Thanks a lot, so you comment I should use divs on the images but how would I do to move those rectangles or change the size (divs) ? – Alexd2 Aug 25 '20 at 16:08
  • I'll prefer to use divs because I remember having some trouble with canvas / imagemaps. If you want to capture drag and drop events, the logic will be similar to above code - you'll need to addEventHandler for mousedown, mousemove, and mouseup. Check this page : https://stackoverflow.com/questions/6042202/how-to-distinguish-mouse-click-and-drag – ankur1812 Aug 25 '20 at 20:17
  • Thanks you for your recomendations, I need search about as capture the coord of div when drag over image. for example: – Alexd2 Aug 25 '20 at 21:25