0

I'm trying to make the following:

Fit a HUGE image within a small div element keeping aspect ratio.
But without using the CSS trick like max-width. Manually settings the width/height to the correct values.

This is the easiest way of me explaining what I'm trying to do.
I got the following values:

Original width/height of the image.
Target div's width/height.

I tried the following example to make it fit within the parent element.

if(ratio < 1) {
    setWidth = Math.round((targetH * ratio));
} else {
    setHeight = Math.round((targetW / ratio));
}

Which looks on the aspect ratio and resize it using that.
Works fine as long as aspect ratio is under 1. If it goes above it height starts to be all messed up. Also seems to jump when you got from 0.99 to 1 with quite a amount of extra height.

danniehansenweb
  • 465
  • 4
  • 14

1 Answers1

0

Joe let me on the right trail with the link he sent to another stackoverflow question. The following code is what i ended up using.

"width" being the current width of the element to scale.
"height" being the current heightof the element to scale.
"targetW" being the max width of the scale.
"targetH" being the max height of the scale.

Fits the element perfectly within the parent element. No matter what aspect ratio.

if(width > targetW){
    ratio = targetW / width;
    height = height * ratio;
    width = width * ratio;
}

if(height > targetH){
    ratio = targetH / height;
    width = width * ratio;
    height = height * ratio;
}

Thanks to @Joe

danniehansenweb
  • 465
  • 4
  • 14