LoginSignup
6
6

More than 5 years have passed since last update.

画像をコンテナに合わせて拡縮させる計算方法

Last updated at Posted at 2013-05-13

jQueryプラグインなどを作るときや、スクラッチ開発の時によく忘れるのでメモ。

marginpaddingborder-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)
6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6