Search code examples
javascripthtmlcssimagescale

Scale div into div like background image


I'm working on a web app and now facing a rather tricky task. I have an image that I have to add overlay for.

Let's say I have an image of a car. I need to add values, like outside and inside temperature, on top of the car image.

It would be easy to add fixed pixel offsets for those temperature labels, but the image need to be scalable to every screen height and width-wise. I can't think of easy way to scale div into div exactly as "background-size:contain;" does for images.

Could someone point me to right tracks before I write complex javascript scaling logic?


Solution

  • ww = window width
    wh = window height
    ow = Original Width of your image
    oh = Original Height of your image
    nw = New Width of your image
    nh = New Height of your image
    mt = Margin top to adjust image to the screen vertically
    ox = overlay location x coordinate according to original size of the image
    oy = overlay location y coordinate according to original size of the image
    nox = New ox
    noy = new oy
    sf = scaling factor
    

    based on screen size you'll have a scaling factor for your image.

    sf = ww / ow -> we find our scaling factor
    nh = oh * sf -> then calculate our new image height
    mt = (oh - nh) / 2 -> amount we need to shift image up to center screen
    nox = ox * sf -> new overlay x coordinate
    noy = (oy * sf) - mt -> new overlay y coordinate
    

    edit

    if image is too wide then this logic needs to be adjusted to shift image horizontally not vertically

    edit 2

    If you're targeting modern browsers only, then you can use CSS transform: scale(sx[, sy]); . This will re-size your DIV and all it's content proportionally Use transform: scale() with transform-origin: 0 0; to re-size from top left corner.