htmlcssimagemap

how to scale image mapping?


hopefully, I can explain this well, I have an image that is 1920 by 1080, and it scales depending on window size. The problem is the image mapping doesn't scale as well, the coordinates are absolute and don't scale, how do I fix this?

<img class="overimage" src="day1_roomstart.png" usemap="#overimage">

<map name="overimage">
    <area shape="rect" coords="451, 122, 658, 254" href="menu.html">
</map>

here's the CSS too:

.overimage {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  -o-object-fit: cover;
  object-fit: cover;
  -o-object-position: center;
  object-position: center;
  z-index: 10;
}

Solution

  • I don't think there is a way to do it with pure html and css alone. But you can do it by leveraging the ResizeObserver api from js.

    const image = document.querySelector('.overimage')
    const area = document.querySelector('map[name="overimage"] > area')
    
    function setCoords() {
     const width = image.clientWidth
     const height.value = image.clientHeight
     area.setAttribute('coords', `${width/4}, ${height/4}, ${3*width/4}, ${3*height/4}`)
     // or something else computed from height and width
    }
    
    setCoords()
    new ResizeObserver(setCoords).observe(image)
    

    When area is used to define a rectangular clickable zone, the coords are "x1, y1, x2, y2". Where x1, y1 are the coordinates of the top left corner of the rectangle inside the image and x2, y2 are for the bottom right corner. My example above is set so that the rectangle is 25% smaller than the image while staying centered.

    Attempt to represent the area inside the image

    Depending on what you want you'd use another formula. Also the area doesn't have to be rectangular (see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area)