https://github.com/shironeko1337/auto-img
Recently I've working on a side project for building a shopify online store. Most of the time, there are some back and forth between me and the client over issues like styling and layout. Those are something I can handle because finally they all converted to things like CSS rules, DOM structure.
However, there is one thing that both my client and me believes should be an easy task but didn't end up so. That is to show an image in a responsive layout.
When you wants to show a photo with the product in the center, normally you wants the source photo to have the same dimension of the image element or image container element. For example, for this image:
It's easy to use object-fit: cover; or background-size: auto auto; background-position: center; to center the image on all size of screens.
However, things become tricky when the part that we want user to focus is not in the center of the image.
If we scale the image down proportionally with the container, then it would probably become distroted which is apparently not desirable. And if we manully control the image size, how do we make sure the most important part is always fully visible even within in a much smaller container.
Apparently we don't want to see that:

So, how about we do this instead:
- Draw a rectangle for the most important part we want user to focus on.
- Adjust image to make sure the focus is centered and fully visible.
- If there are empty parts of the image container, scale or shift the image while preserving the focus fully visible.
All we care is the focus area:

(An image of original size 1000 x 667 shown in a 781 x 602 container with focus area predefined)
You can play around with the algorithm in https://shironeko1337.github.io/auto-img/playground.html
Finally, I made a web component containing all things together, the centering algorithm, the resize handler and the placeholder, the react and vue wrappers: https://github.com/shironeko1337/auto-img
Glad to know if it helps for the content focused websites to have content aware responsive images.


Top comments (0)