Yes, you can determine the scale factor of an image using JavaScript. When you set height: 90%, the image is scaled relative to its container's height, and you can compare the rendered dimensions to the original dimensions.
Here's how to calculate the scale factor:
// Get the image element
const img = document.querySelector('img'); // or document.getElementById('your-image-id')
// Get the natural (original) dimensions
const naturalWidth = img.naturalWidth;
const naturalHeight = img.naturalHeight;
// Get the rendered (displayed) dimensions
const renderedWidth = img.offsetWidth; // or img.clientWidth
const renderedHeight = img.offsetHeight; // or img.clientHeight
// Calculate scale factors
const scaleFactorHeight = renderedHeight / naturalHeight;
const scaleFactorWidth = renderedWidth / naturalWidth;
// Overall scale factor (should be the same if aspect ratio is maintained)
const scaleFactor = scaleFactorHeight;
console.log(`Original size: ${naturalWidth}x${naturalHeight}px`);
console.log(`Rendered size: ${renderedWidth}x${renderedHeight}px`);
console.log(`Scale factor: ${(scaleFactor * 100).toFixed(2)}%`);
Important notes:
- Wait for image load: Make sure the image is fully loaded before accessing
naturalWidth and naturalHeight:
img.addEventListener('load', function() {
// Calculate scale factor here
});
-
Aspect ratio: If you only set height: 90% without setting width, the browser will typically maintain the aspect ratio automatically, so both width and height will be scaled by the same factor.
-
Alternative methods to get dimensions:
getBoundingClientRect(): Returns the rendered size including any CSS transforms
getComputedStyle(): Gets the computed CSS values
Example with complete implementation:
function getImageScaleFactor(imgElement) {
if (!imgElement.complete) {
imgElement.addEventListener('load', () => getImageScaleFactor(imgElement));
return;
}
const rect = imgElement.getBoundingClientRect();
const scaleFactor = rect.height / imgElement.naturalHeight;
return {
originalSize: {
width: imgElement.naturalWidth,
height: imgElement.naturalHeight
},
renderedSize: {
width: rect.width,
height: rect.height
},
scaleFactor: scaleFactor,
scalePercentage: (scaleFactor * 100).toFixed(2) + '%'
};
}
This will tell you exactly how much your image has been scaled from its original pixel dimensions.