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不会丢失宽高比 - 将其裁剪成方形。 –