[JS]サイズが不明な画像を指定したエリアにフィットさせたり、配置を調整できるスクリプト -Image Scale
Post on:2013年8月20日
サイズが不明な画像を指定したエリアにアスペクト比を維持したまま、縮小させてフィットさせて配置したり、上下左右寄せに配置させることができるjQueryのプラグインを紹介します。

Image Scaleのデモ
デモでは大きな画像のアスペクト比を維持したまま、小さいエリアにフィットさせて表示したり、トリミングして位置調整することもできます。

元の画像は650x432で、250x250のエリアに表示させます。

そのまま配置したデモ
スクリプトはオプションで、さまざまなフィットを選択できます。
デフォルトの「fit」では、単に指定エリアにフィットさせるだけです。

デフォルトの「fit」
アスペクト比を維持したまま、フィットさせることができます。

画像の短い辺に合わせて、フィット
フィットさせた際に、配置を調整することもできます。

フィットさせて、左寄せ
長い辺に合わせるもできます、

画像の長い辺に合わせて、フィット
Image Scaleの使い方
Step 1: 外部ファイル
head内にjquery.jsと当スクリプトを外部ファイルとして記述します。
<head> ... <script src="jquery.js" type="text/javascript"></script> <script src="image-scale.js" type="text/javascript"></script> </head>
Step 2: HTML
大きさを調整したい画像に「class=scale」を加えます。
<div class="image-container"> <img class="scale" src="img/example.jpg"> </div>
さらに、画像の位置などを設定する場合はdata属性を加えます。
<div class="image-container"> <img class="scale" data-scale="best-fit-down" data-align="center" src="img/example.jpg"> </div>
Step 3: JavaScript
jQueryのセレクタで画像を指定し、スクリプトを実行します。
$(function() { $("img.scale").imageScale(); });
オプション
data属性でさまざまな設定できます。
- fill
- 指定したエリアに画像をいっぱいに表示にします。
- best-fill
- 画像のアスペクト比を維持したまま、指定したエリアの縦横の短い方に合わせて画像を表示します。
- best-fit
- 画像のアスペクト比を維持したまま、指定したエリアの縦横の長い方に合わせて画像を表示します。
- best-fit-down
- 「best-fit」と同様で、指定したエリアより小さい場合はそのまま表示します。
- none
- 調整せずに、そのまま表示します。
また、「data-align」を使って、配置を設定できます。
- left
- right
- center
- top
- bottom
- top-left
- top-right
- bottom-left
- bottom-right
sponsors