作ったもの
Image Math — https://sen.ltd/portfolio/image-math/
- アスペクト比計算(自動簡約)
- 幅指定・高さ指定でのスケーリング(比率保持)
- fit inside / cover outside の計算
- ターゲット比率への中央クロップ
- プリセット: SNS / アイコン / ディスプレイ解像度
- PNG / JPEG / WebP のファイルサイズ概算
- 近いスタンダード比率の検出
vanilla JS、ゼロ依存、ビルド不要。node --test で 39 ケース。
GCD で比率を簡約
1920×1080 の比率は 16:9。ユークリッドの互除法で GCD を求めて割る:
export function gcd(a, b) {
while (b) [a, b] = [b, a % b];
return a;
}
fit vs cover
object-fit: contain と object-fit: cover の算術版:
// fit: 両辺が max 以下に収まる最大
const scale = Math.min(maxW / srcW, maxH / srcH);
// cover: 両辺が min 以上をカバーする最小
const scale = Math.max(minW / srcW, minH / srcH);
同じ形、反対方向。
プリセット
OGP(1200×630) / Twitter(1200×675) / Instagram 正方形(1080×1080) / Instagram ストーリー(1080×1920) / YouTube サムネ(1280×720) / iOS アイコン(1024×1024) など。
シリーズ
100+ 公開ポートフォリオ シリーズの #49 です。
- 📦 リポジトリ: https://github.com/sen-ltd/image-math
- 🌐 デモ: https://sen.ltd/portfolio/image-math/
- 🏢 会社: https://sen.ltd/
