Skip to content

Instantly share code, notes, and snippets.

@YusukeHirao
Created May 13, 2013 14:45
Show Gist options
  • Save YusukeHirao/5568829 to your computer and use it in GitHub Desktop.
Save YusukeHirao/5568829 to your computer and use it in GitHub Desktop.
画像をコンテナに合わせて拡縮させる計算方法 ref: http://qiita.com/items/785e331be62f15db0fa4
# 画像の情報
imgWidth = $img.width()
imgHeight = $img.height()
imgAspectRatio = containerWidth / containerHeight
# コンテナの情報
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment