SVGやcanvasを使えば確かそのままトリミングもできた気がするが、別にそこまでしたくない用の関数。画像のオリジナルサイズを取得し計算する感じだ。面倒なのでjQueryを使う。
var frameWidth = 700; var frameHeight = 400; $('li').css({ "overflow" : "hidden" }); $('div.resize img').each(function(){ $(this).load(function(){ var nWidth = this.naturalWidth || getNaturalSize(this).width; var nHeight = this.naturalHeight || getNaturalSize(this).height; if(nHeight < nWidth * (frameHeight / frameWidth)){ this.width = nWidth * frameHeight / nHeight; this.height = frameHeight; $(this).css({ "width" : nWidth * frameHeight / nHeight + 'px', "height" : frameHeight + 'px', "position" : "relative", "left" : -((nWidth * frameHeight / nHeight) - frameWidth) / 2 + 'px' }); } else{ this.width = frameWidth; this.height = nHeight * frameWidth / nWidth; $(this).css({ "width" : frameWidth + 'px', "height" : nHeight * frameWidth / nWidth + 'px', "position" : "relative", "top" : -((nHeight * frameWidth / nWidth) - frameHeight) / 2 + 'px' }); } }); });
以下の部分でブラウザ分岐をしている。IEとOpera以外はimgオブジェクトにオリジナルのサイズが格納されたプロパティ(naturalWidth、naturalHeight)を持つ。
var nWidth = this.naturalWidth || getNaturalSize(this).width;//ff : ie var nHeight = this.naturalHeight || getNaturalSize(this).height;//ff : ie
getNaturalSize関数は以下のようになる。
var getNaturalSize = function(image){ var w, h, key = "actual", run, mem; if(window.opera){ } if (image[key] && image[key].src === image.src) { return image[key]; } run = image.runtimeStyle; mem = { "w" : run.width, "h" : run.height }; // keep runtimeStyle run.width = "auto"; // override run.height = "auto"; w = image.width; h = image.height; run.width = mem.w; // restore run.height = mem.h; image[key] = { "width" : w, "height" : h, "src" : image.src }; return image[key]; // bond };
ちなみにOperaには対応していない。