Search code examples
htmlcssoverflowtransform

Scrolling into -y and -x of overflowed image


I have an image that scales when I hover over it, the excess image is hidden (see example code).

I want the image to scale from the centre so I use transform-origin: 50% 50%

The problem is; I want to be able to drag/scroll around the whole image in its transformed state, however, I can't scroll up or to the left of the centre of the image.

If I use transform-origin: 0% 0% I can see the whole image but (obviously) it no longer transforms from the centre of the image.

Any suggestions on how I can access the -y and -x space of the image whilst keeping the transform-origin in the centre?

/* Map Image
  –––––––––––––––––––––––––––––––––––––––––––––––––– */
#MapBase {
  position: relative;
  left: 100px;
  width: 100%;
  height: auto;
  max-width: 450px;
  max-height: 550px;
  z-index: 1;
  visibility: visible;
  overflow: scroll;
  }

#MapBase img {
  display: block;
  transition: transform .6s;
}
#MapBase:hover img {
  transform: scale(2);
  transform-origin: 50% 50%;
}
<div id="MapBase" class="map-container map-base dragscroll">
      <img src="https://via.placeholder.com/450x550" class="map">


Solution

  • I was lucky enough to find someone who had a fix for this problem. I'll share the code below for anyone who might land here with a similar request.

    I've replaced the names of things my code used with myArray1 myArray2, please someone correct me if this is the incorrect terminology.

    const myArray1 = document.querySelector('#');
    const myArray2 = document.querySelector('#');
    let hovering = false;
    myArray1.addEventListener('mousemove', () => {
      if (hovering) {
        return;
      }
    
      myArray2.style.zoom = '200%';
      myArray1.scrollTo({
        top: myArray1.scrollHeight / 4,
        left: myArray1.scrollWidth / 4,
      });
    
      hovering = true;
    })
    
    myArray1.addEventListener('mouseleave', () => {
      hovering = false;
      myArray2.style.zoom = '100%';
      myArray1.scrollTo({
        top: myArray1.scrollHeight / 4,
        left: myArray1.scrollWidth / 4,
      })
    })