jQueryプラグインなどを作るときや、スクラッチ開発の時によく忘れるのでメモ。
※margin
やpadding
、border-width
が0以外のときは計算が狂う可能性があるので注意。
# 画像の情報
imgWidth = $img.width()
imgHeight = $img.height()
imgAspectRatio = imgWidth / imgHeight
# コンテナの情報
containerWidth = $container.width()
containerHeight = $container.height()
containerAspectRatio = containerWidth / containerHeight
# 画像の拡縮率の算出
# アス比が1以上なら横長/1以下なら縦長
# コンテナが横長
if 1 < containerAspectRatio
# 画像が横長 もしくは コンテナのアス比の方が大きい
if 1 < imgWidth and imgAspectRatio < containerAspectRatio
scale = containerHeight / imgHeight
# 画像が縦長
else
scale = containerWidth / imgWidth
# コンテナが縦長
else
# 画像が横長 もしくは 画像のアス比の方が大きい
if 1 < imgHeight and containerAspectRatio < imgAspectRatio
scale = containerWidth / imgWidth
else
scale = containerHeight / imgHeight
# 画像の幅と高さ
newWidth = imgWidth * scale
newHeight = imgHeight * scale
# スタイルの反映
$img.css
width: newWidth
height: newHeight
# おまけ コンテナに対してセンタリングをしたい時
$img.css
top: (containerHeight / 2) - (newHeight / 2)
left: (containerWidth / 2) - (newWidth / 2)