-
Notifications
You must be signed in to change notification settings - Fork 0
/
scale-image.js
77 lines (57 loc) · 2.42 KB
/
scale-image.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<script>
// This start scaling right after DOM is loaded - and we'll await actual image downloads inside the code of scaleImages
$(function() { scaleImages() });
// Smart scaling and cropping on the fly. Do not tracking page resize yet!
function scaleImages() {
// Wait till images fully loaded
var deferreds = [];
$('.scale').each(function() {
if (!this.complete) {
var deferred = $.Deferred();
$(this).one('load', deferred.resolve);
deferreds.push(deferred);
}
});
$.when.apply($, deferreds).done(function() {
$('.scale').each(function(i, item) {
var nw = $(item).prop("naturalWidth");
var nh = $(item).prop("naturalHeight");
var w = $(item).prop("width");
var h = $(item).prop("height");
var wanted = h; // Scale image by container height
var imageRatio = nw / nh;
var divRatio = w / h;
var factor = nw / w; // Suppose that image width is more than container
var neww = 0;
var newh = 0;
var newTopMargin = 0;
var newLeftMargin = 0;
// Image is BIGGER than container
if (factor >= 1) {
if (divRatio > imageRatio) {
neww = w;
newh = nh / factor;
newTopMargin = wanted - newh;
} else {
newh = wanted;
neww = nw / (nh / wanted);
newLeftMargin = w - neww;
}
// Container is BIGGER than image
} else {
if (divRatio > imageRatio) {
neww = w;
newh = h / factor;
newTopMargin = - (newh - wanted);
} else {
newh = wanted;
neww = nw / (nh / wanted);
newLeftMargin = w - neww;
}
}
$(item).css({'width': neww, 'height': newh, 'margin-top': newTopMargin, 'margin-left': newLeftMargin });
$(item).removeClass('scale'); // Do not scale when new block of news will be loaded
});
});
}
</script>