Created
May 3, 2012 17:06
-
-
Save calebds/2587296 to your computer and use it in GitHub Desktop.
Downloads, re-sizes and centers an image to fit a display area, with padding.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Downloads, re-sizes and centers an image to fit a display area, with padding. Uses jQuery. | |
* | |
* Example markup + CSS: | |
* | |
* <div id="gallery-slide"></div> | |
* | |
* #gallery-slide { | |
* width: 200px; | |
* height: 400px; | |
* background: black; | |
* text-align: center; | |
* } | |
* | |
* DEMO - http://jsfiddle.net/paislee/Da8FM/2/ | |
* | |
*/ | |
var SLIDE_W = $('#gallery').width(); | |
var SLIDE_H = $('#gallery').height(); | |
var PADDING = 10; // px | |
var max_w = SLIDE_W - 2*PADDING; | |
var max_h = SLIDE_H - 2*PADDING; | |
var test = new Image(); | |
$(test).load(function() { | |
adjustFullIMG(test); | |
$('#gallery').append(test); | |
}); | |
test.src = 'http://www.dailyinterestingfacts.com/wp-content/uploads/2011/11/giraffe-facts-Heart-of-giraffe1.jpg'; | |
/** | |
* Resize image proportionally to fit slide area | |
*/ | |
function adjustFullIMG(img) { | |
var jq_img = $(img); | |
var temp_w = img.width, temp_h = img.height; | |
var ratio = temp_w / temp_h; | |
if (img.width > max_w) { | |
temp_w = max_w; | |
temp_h = temp_w / ratio; | |
} | |
if (temp_h > max_h) { | |
temp_h = max_h; | |
} | |
var margin_top = (max_h - temp_h) / 2; | |
jq_img.css('margin-top', margin_top); | |
jq_img.height(temp_h); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment