jQuery プラグイン開発のための習作

画像の一部をランダムで切り出すプラグイン

の下書き。



;(function($) {
$.fn.extend({
myThumbnail: function(options){
options = $.extend({
'width':100,
'height':100,
'unit':'px',
'appendclass':'my-thumbnails',
'position':getPosition
},options);

$(this).each( function(){

$(this).wrap('<div class="'+options.appendclass+'"></div>');

var defImage = $(this);

var imgPreloader = new Image();

//切り抜くサイズ
var width = options.width;
var height = options.height;

var unit = options.unit;

imgPreloader.onload = function(){

//オリジナルサイズ
var oWidth = imgPreloader.width;
var oHeight = imgPreloader.height;

defImage.css({
'opacity':'0.0',
'width':width+unit,
'height':height+unit
}).show();

//座標設定
var position;

if( $.isFunction(options.position) ){
var arg = {'width':width,'height':height,
'oWidth':oWidth,'oHeight':oHeight};

position = options.position(arg)
}else{
position = options.position;
}

defImage.parent('div.'+options.appendclass).css({
'width': width+unit,
'height': height+unit,
'background-image':'url('+imgPreloader.src+')',
'background-repeat':'no-repeat',
'background-position':position.x+unit+' '+position.y+unit
});
}
imgPreloader.src = $(this).attr('src');
});
}
});

function getPosition(opt)
{
return {'x': getPositionRandom(opt.oWidth,opt.width),
'y':getPositionRandom(opt.oHeight,opt.height)};
}
function getPositionRandom(original,fil)
{
if(original > fil){
return (-1) * Math.ceil(Math.random()*(original-fil));
}else{
return ( fil - original ) /2;
}
}
})(jQuery);


呼び出し。


<img class="thumbnail" src="....." style="visibility:hidden" />


$(document).ready(function(){
$('img.thumbnail').myThumbnail({width:100,height:100});
}



右クリックでちゃんと画像の扱いがされるようにする。
切り抜きのアルゴリズムは呼び出し側から設定できるようにする。



みたいな。
そんな感じで。