1

Im trying to match some vectors above a Image comonent. In order to do this pixel-perfect, I need to know the size of the image displayed inside Image component.

At this point I have the width and height of the component layout, but can't figure out how to calculate the width and height of the image once is inside the Image component.

I tried to calculate the following way with the proportions of with and viceversa, but there are some cases (specially vertical image) where this does not work.

/*
    Calculate proportional width of displayed image:
    
    photo.width -> width
    photo.height -> x
*/
var x = (width * photo.height) / photo.width;
/*
    calculate proportional height of displayed image:
    
    photo.height -> height
    photo.width -> y
*/
var y = (height * photo.width) / photo.height;

Karlo A. López
  • 2,548
  • 3
  • 29
  • 56

1 Answers1

0

Use the .clientWidth and .clientHeight properties of the image element to determine its actual scaled width and height. If for some reason that's not an option, you can do the calculation yourself:

If ( photo.width / photo.height ) > ( containerWidth / containerHeight ) then the photo has a wider aspect ratio than the container and can be scaled to fit full-width in the container, with letterboxing (blank space above and below). The new width and height of the photo is:

newPhotoWidth = containerWidth
newPhotoHeight = containerWidth * ( photo.height / photo.width )

For example, if the container is 500x400 and the photo is 300x50:

newPhotoWidth = 500
newPhotoHeight = 83.33 // i.e. 500 * ( 50 / 300 )

If ( photo.width / photo.height ) > ( containerWidth / containerHeight ) then the photo has a narrower aspect ratio than the container and can be scaled to fit full-height in the container, with letterboxing on the left and right (as shown in your example image). The new width and height of the photo is:

newPhotoWidth = containerHeight * ( photo.width / photo.height )
newPhotoHeight = containerHeight

For example, if the container is 500x400 and the photo is 50x300:

newPhotoHeight = 66.66  // i.e. 400 * ( 50 / 300 )
newPhotoWidth = 400
kmoser
  • 8,780
  • 3
  • 24
  • 40