Background fitting the browser and image ratio
| 1 min read
Here is an example to show a element like a background, a image in a portfolio or whatever and make it fitting the browser.
In the demo you can choose three modes.
Mode Fit
The picture is fitting the browser regardless the original ratio. The formula is simple:
imagePositionX = 0
imagePositionY = 0
imageWidth = stageWidth
imageHeight = stageHeight
Mode Out (I called it like that because you'll miss a part of the picture)
The picture is fitting the browser as well but we keep the ratio, we'll miss a part of the picture at the right or the bottom in my example.
ratio = initialImageWidth / initialImageHeight
newWidth = stageWidth
newHeight = stageHeight
if (stageWidth / ratio < stageHeight) newWidth = stageHeight * ratio;
else newHeight = stageWidth / ratio;
imagePositionX = 0
imagePositionY = 0
imageWidth = newWidth
imageHeight = newHeight
Mode In
The image is fitting the browser, we also keep the ratio but we show the whole picture, we'll have a gap around depending of the size of the area.
ratio = initialImageWidth / initialImageHeight
newWidth = stageWidth
newHeight = stageHeight
if (stageWidth / ratio > stageHeight) newWidth = stageHeight * ratio
else newHeight = stageWidth / ratio
imageWidth = newWidth
imageHeight = newHeight
imagePositionX = (stageWidth * .5) - (imageWidth * .5)
imagePositionY = (stageHeight * .5) - (imageHeight * .5)