Skip to content

Instantly share code, notes, and snippets.

@hagino3000
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hagino3000/4560e4be81e55749314c to your computer and use it in GitHub Desktop.
Save hagino3000/4560e4be81e55749314c to your computer and use it in GitHub Desktop.
画像の真ん中をいい感じに切り取るスクリプト
define(['utils', 'template'], function (Utils, JST) {
'use strict';
function render() {
// テンプレート使ってレンダリングする例
$('#target').html(JST['app/templates/fuga.ejs'], {images: [],....});
// 画像を60px * 60pxの枠に納めるとする
var adjustFn = Utils.createImageAdjustFn(60, 60);
$('#target .profile img').on('load', function() {
// サイズを調節したい奴をセレクタで指定してloadイベントで処理する
adjustFn($(this)).removeClass('need_adjust');
});
}
render();
});
define([], function () {
'use strict';
/**
* 画像のサイズ調節用の関数を返す
* 親のBox要素は次のスタイルを指定しておく
*
* - overflow: hidden
* - position: relative
* - width: 任意の値
* - height: 任意の値
* /
function createImageAdjustFn(boxWidth, boxHeight) {
return function($img) {
var width = $img.width();
var height = $img.height();
if (width > height) {
// 横長の画像の場合は縦をフルに使う
$img.css({
'height': boxHeight,
'left': -1 * Math.floor(boxWidth/2 * (width/height - 1)),
'position': 'absolute'
});
} else {
// 縦長の画像の場合は横をフルに使う
$img.css({
'width': boxWidth,
'top': -1 * Math.floor(boxHeight/2 * (height/width - 1)),
'position': 'absolute'
});
}
return $img;
}
}
return {
createImageAdjustFn: createImageAdjustFn
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment