Skip to content

Instantly share code, notes, and snippets.

@wgkoro
Last active October 19, 2016 10:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wgkoro/5527114 to your computer and use it in GitHub Desktop.
Save wgkoro/5527114 to your computer and use it in GitHub Desktop.
指定サイズ以内の画像幅、高さを算出、img要素にそのサイズを適用するスクリプト
/**
* 指定サイズ以内の画像幅、高さを算出、
* img要素にそのサイズを適用する
*
* 使い方:
*
* 例) 幅150px, 高さ200px以内で画像を表示する
* var img = document.createElement('img');
* img.src = 'http://hoge.com/img/fuga.jpg';
* imgResize.resize(img, 150, 200);
*/
var imgResize = {
w_limit : null,
h_limit : null,
org_img : document.createElement('img'),
resize : function(img, w_limit, h_limit){
if(! img) return;
this.org_img.src = img.src;
var w = this.org_img.width;
var h = this.org_img.height;
this.w_limit = w_limit;
this.h_limit = h_limit;
if(w <= w_limit && h <= h_limit) return img;
var size = this.getSize(w, h);
img.width = size.w;
img.height = size.h;
return img; // テスト用に戻す
},
getSize : function(w, h){
if(w > this.w_limit){
width_ratio = this.w_limit/w;
w = this.w_limit;
h = h * width_ratio;
}
if(h > this.h_limit){
height_ratio = this.h_limit/h;
h = this.h_limit;
w = w * height_ratio;
}
return {
w : Math.round(w),
h : Math.round(h)
};
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment