function ScaleImage(srcwidth, srcheight, targetwidth, targetheight, fLetterBox, xOffSet, yOffSet) {
\t var result = { width: 0, height: 0, fScaleToTargetWidth: true };
\t if ((srcwidth <= 0) || (srcheight <= 0) || (targetwidth <= 0) || (targetheight <= 0)) {
\t \t return result;
\t }
\t // scale to the target width
\t var scaleX1 = targetwidth;
\t var scaleY1 = (srcheight * targetwidth)/srcwidth;
\t // scale to the target height
\t var scaleX2 = (srcwidth * targetheight)/srcheight;
\t var scaleY2 = targetheight;
\t // now figure out which one we should use
\t var fScaleOnWidth = (scaleX2 > targetwidth);
\t if (fScaleOnWidth) {
\t \t fScaleOnWidth = fLetterBox;
\t }
\t else {
\t fScaleOnWidth = !fLetterBox;
\t }
\t if (fScaleOnWidth) {
\t \t result.width = Math.floor(scaleX1);
\t \t result.height = Math.floor(scaleY1);
\t \t result.fScaleToTargetWidth = true;
\t }
\t else {
\t \t result.width = Math.floor(scaleX2);
\t \t result.height = Math.floor(scaleY2);
\t \t result.fScaleToTargetWidth = false;
\t }
\t //result.targetleft = Math.floor((targetwidth - result.width)/2);
\t //result.targettop = Math.floor((targetheight - result.height)/2);
\t result.targetleft = Math.floor((targetwidth - result.width)/2 - xOffSet);
\t result.targettop = Math.floor((targetheight - result.height)/2 - yOffSet);
\t return result;
}
function OnImageLoad(evt, xOffSet = 0, yOffSet = 0) {
\t var img = evt.currentTarget;
\t // what's the size of this image and it's parent
\t var w = $(img).width();
\t var h = $(img).height();
\t var tw = $(img).parent().width();
\t var th = $(img).parent().height();
\t // compute the new size and offsets
\t var result = ScaleImage(w, h, tw, th, false, xOffSet, yOffSet);
\t // adjust the image coordinates and size
\t img.width = result.width;
\t img.height = result.height;
\t $(img).css("left", result.targetleft);
\t $(img).css("top", result.targettop);
}
.result {
width: 250px;
height: 250px;
border: thick solid #666666;
overflow: hidden;
position: relative;
border-radius: 50%;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
No offset:
<div class='result'>
\t <img src="http://i.imgur.com/22W12EQ.jpg" style="position: absolute;" onload="OnImageLoad(event, 0, 0);"/>
</div>
Y offset:
<div class='result'>
\t <img src="http://i.imgur.com/22W12EQ.jpg" style="position: absolute;" onload="OnImageLoad(event, 0, 30);"/>
</div>
順便說一句,這是我女兒的照片,所以版權是我的! :) –
你說*有沒有辦法將圖像變成方形*。你是說你可以將矩形圖像調整爲正方形並丟失圖像的寬高比嗎? –
@FrankFajardo不會丟失寬高比 - 將其裁剪成方形。 –