Last active
September 25, 2019 02:26
-
-
Save BiosSun/6920202 to your computer and use it in GitHub Desktop.
矩形缩放算法,JS 版。http://jsfiddle.net/TJjJd/1/
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
/** | |
* 将原尺寸缩放使之能够填充目标尺寸,缩放后尺寸小于或等于目标尺寸, | |
* 且有一边与原尺寸相同。 | |
* @param w1 目标尺寸 - 宽度 | |
* @param h1 目标尺寸 - 高度 | |
* @param w2 原尺寸 - 宽度 | |
* @param h2 原尺寸 - 高度 | |
*/ | |
function contain(w1, h1, w2, h2) { | |
var ar1 = w1 / h1, // aspect ratio | |
ar2 = w2 / h2, | |
tw, th, | |
tz; | |
if (ar1 > ar2) { | |
tz = h1 / h2; | |
tw = w2 * tz; th = h1; | |
} | |
else if (ar1 < ar2) { | |
tz = w1 / w2; | |
tw = w1; th = h2 * tz; | |
} | |
else { | |
tz = w1 / w2; | |
tw = w1; th = h1; | |
} | |
return { width: tw, height: th, zoom: tz }; | |
} |
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
/** | |
* 将原尺寸缩放使之能够填充目标尺寸,缩放后尺寸大于或等于目标尺寸, | |
* 且有一边与原尺寸相同。 | |
* @param w1 目标尺寸 - 宽度 | |
* @param h1 目标尺寸 - 高度 | |
* @param w2 原尺寸 - 宽度 | |
* @param h2 原尺寸 - 高度 | |
*/ | |
function cover(w1, h1, w2, h2) { | |
var ar1 = w1 / h1, // aspect ratio | |
ar2 = w2 / h2, | |
tw, th, | |
tz; | |
if (ar1 > ar2) { | |
tz = w1 / w2; | |
tw = w1; th = h2 * tz; | |
} | |
else if (ar1 < ar2) { | |
tz = h1 / h2; | |
tw = w2 * tz; th = h1; | |
} | |
else { | |
tz = w1 / w2; | |
tw = w1; th = h1; | |
} | |
return { width: tw, height: th, zoom: tz }; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment