Skip to content

Commit 6475017

Browse files
author
Sepand Parhami
authored
Handle object-fit gracefully for older browsers. (#12)
This fixes an Error being thrown in IE since it does not support object-fit.
1 parent 77706e0 commit 6475017

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

src/img-dimensions.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,11 +102,15 @@ function getDimensionsForObjectFitScaleDown(
102102
* that constrains the size with the CSS `object-fit` property.
103103
* @param img The HTMLImageElement
104104
* @param containerSize The size of the container element.
105+
* @param objectFit An optional object-fit value to use. Defaults to the
106+
* `img`'s current `object-fit`.
105107
* @return The width/height of the "actual" image.
106108
*/
107109
export function getRenderedDimensions(
108-
img: HTMLImageElement, containerSize: Size): Size {
109-
const objectFit = getComputedStyle(img).getPropertyValue('object-fit');
110+
img: HTMLImageElement,
111+
containerSize: Size,
112+
objectFit: string|null = getComputedStyle(img).getPropertyValue('object-fit'),
113+
): Size {
110114
const naturalSize = {
111115
width: img.naturalWidth,
112116
height: img.naturalHeight,
@@ -123,6 +127,11 @@ export function getRenderedDimensions(
123127
return getDimensionsForObjectFitNone(naturalSize);
124128
case 'scale-down':
125129
return getDimensionsForObjectFitScaleDown(naturalSize, containerSize);
130+
case '':
131+
case null:
132+
// For browsers that do not support `object-fit`, default to `fill`
133+
// behavior.
134+
return getDimensionsForObjectFitFill(containerSize);
126135
default:
127136
throw new Error(`object-fit: ${objectFit} not supported`);
128137
}

src/test-img-dimensions.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,24 @@ describe('getDimensions', () => {
7474
});
7575
});
7676

77+
describe('unsupported object-fit', () => {
78+
it('should return the requested dimensions for blank', async () => {
79+
await updateImg(img, 'fill', threeByFourUri);
80+
81+
const {width, height} = getRenderedDimensions(img, dimensions(10, 10), '');
82+
expect(width).to.equal(10);
83+
expect(height).to.equal(10);
84+
});
85+
86+
it('should return the requested dimensions for null', async () => {
87+
await updateImg(img, 'fill', threeByFourUri);
88+
89+
const {width, height} = getRenderedDimensions(img, dimensions(10, 10), null);
90+
expect(width).to.equal(10);
91+
expect(height).to.equal(10);
92+
});
93+
});
94+
7795
describe('object-fit: contain', () => {
7896
it('should return the correct dimensions when constrained by width', async () => {
7997
await updateImg(img, 'contain', threeByFourUri);

0 commit comments

Comments
 (0)