DEV Community

Cover image for Put Overlays on image and fit in different aspect ratios
Jimmy Yeung
Jimmy Yeung

Posted on

Put Overlays on image and fit in different aspect ratios

Preface

I would not say I am a frontend guy. But most of the time in my company I need to do projects in a fullstack way, meaning that I need to touch the frontend side of work as well. And here comes an interesting problem for me to solve ;D

Problem

We need to highlight certain phrases of an image full of text. We're given sets of (x,y,height,width) of the image. The (x,y,height,width) are in percentage so that we can simply do the following to draw an overlay on the image (See example below for highlighting the text danger and science)

overlay {
    left: x%;
    top: y%;
    height: height%;
    width: width%;
}
Enter fullscreen mode Exit fullscreen mode

Ok so how about next?

What if we need to fit it into a viewport which has different aspect ratio? While at the same time highlighting the same thing as the original one?

Fit into a different viewport

In order to do that, we need to know

  1. which part of the original image should we show, and
  2. how we scale the new positions

Assumptions

  • For simplicity, assume width should always be preserved; as we're fitting a 4629/10110 image to a 700/500 viewport

which part of the original image should we show

The css property background-position comes into handy. And big thanks to the article from https://dev.to/this-is-learning/all-you-need-to-know-about-background-position-3aac, which clearly explains how background-position works. If we know how it works, we could then calculate the new positions by simple maths.

TL;DR

  1. we need to know the minimum y so that we can set that as the new background-position-y
  2. then we need to calculate the new y' and height' after the scaling. (I'm skipping the maths here, but if you are interested, feel free to take a look at the example below)

And at last we could result in something like this ;D

Sum Up

Of course it's not perfect solution. I'm just trying to demo the css properties we can make use of when tackling a problem. There are also other handling/optimisation needed, e.g.

  • what if the highlight (partially) lies outside of the viewport?
  • what if some coordinates cannot fit into the viewport with x unchanged; then we need to scale x too.
  • others...

Love to hear if there're other approaches towards this too!

Top comments (0)