willnguyen1312 / zoom-image

A little yet powerful framework agnostic headless library to zoom images on the web

Home Page:https://willnguyen1312.github.io/zoom-image/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

useZoomImageHover doesn't work if the aspect ratio of the img/container does not match the aspect ratio of the source image

NikitaIT opened this issue · comments

Describe the bug

Reproduction

  1. Go to https://willnguyen1312.github.io/zoom-image/
  2. Click on Hover tab
  3. Set height: 500px; to the image element

W>>H in aspect square

image

H>>W in aspect square (When the source image is 2 times longer than the container, the preview ends in the middle of the image.)

image

I tried to solve it like this.

But the obvious solution is to position the image at its original size inside the container. Unfortunately there is no such thing as display: cover.

      const getMeta = (url: string): Promise<HTMLImageElement> =>
        new Promise((resolve, reject) => {
          const img = new Image();
          img.onload = () => resolve(img);
          img.onerror = (err) => reject(err);
          img.src = url;
        });
      getMeta(current.url).then((x) => {
        createZoomImage(imageContainer, {
          zoomImageSource: current.url,
          customZoom: {
            width: x.naturalWidth / 2,
            height: x.naturalHeight / 2,
          },
          zoomTarget,
          scale: 3,
        });
      });

Reproduction

https://willnguyen1312.github.io/zoom-image/

Used Package Manager

pnpm

Validations

  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • The provided reproduction is available

Hi @NikitaIT, thanks for your feedback. It is a de facto requirement that the aspect ratio of the image and its container be the same. Otherwise, we will get a distorted result. I built the zoom-on-hover image with the mindset that the image's dimensions are already available upfront as it's the best way to avoid Cumulative Layout Shift (CLS).

If you cannot access these values, you have to load the image at runtime. I hope the solution attached will work for you. In summary, I reused the getMeta function of yours and then calculated the right dimensions for the image container. I also updated the library to make it more robust to support your use case. Please feel free to ping me with any more questions or concerns. Thanks :)

https://stackblitz.com/edit/willnguyen1312-zoom-image-3d3kuz?file=package.json,src%2FApp.tsx

Hi @NikitaIT, I'm going to close this issue as it's been inactive for a while. Please feel free to re-open it in case you need any help with it. Thanks so much :)