如何缩放(调整大小)图像保持纵横比javascript

时间:2016-09-30 11:50:10

标签: javascript

我有一些随机尺寸的图像,问题是如何在JavaScript中将其缩放(调整大小)到960×1280,但保持图像原始宽高比:

  • 如果图片大于大于预期尺寸,则按比例缩小(保持宽高比),空白区域将填充透明色。
  • 如果图片比预期尺寸,则不缩放,但居中,空白区域用透明色填充。

我已经阅读过有关此主题的一些内容,但仍然无法解决问题。

这对我不起作用:How to resize images proportionally / keeping the aspect ratio?

更新:在这里工作解决方案,非常感谢@Mr。 Polywhirl Update solution

2 个答案:

答案 0 :(得分:1)

为了找出用于缩放的宽高比,您需要确定哪个尺寸更大。你这样做,你只需将图像的宽度/高度除以观察者的宽度/高度,就可以确定比例因子。

可以通过在查看器中查找缩放图像的偏移来实现居中。

var ctx = document.getElementById('image-viewer').getContext('2d');
var images = [
  'http://i.imgur.com/5PF0Xdi.jpg',
  'http://i.imgur.com/po0fJFT.png',
  'http://i.imgur.com/Ijzdt0o.png'
];
var counter = 0;

// Load a new image after 2 seconds.
setInterval(function() {
  loadScaleAndCenterImage(ctx, images[counter++ % images.length]);
}, 2000);

function loadScaleAndCenterImage(ctx, url) {
  var imageObj = new Image();
  imageObj.onload   = function(e) {
    var ctxWidth    = ctx.canvas.width,
        ctxHeight   = ctx.canvas.height;
    var imgWidth    = imageObj.width,
        imgHeight   = imageObj.height;
    var ratioWidth  = imgWidth  / ctxWidth,
        ratioHeight = imgHeight / ctxHeight,
        ratioAspect = ratioWidth > 1 ? ratioWidth : ratioHeight > 1 ? ratioHeight : 1;
    var newWidth    = imgWidth / ratioAspect,
        newHeight   = imgHeight / ratioAspect;
    var offsetX     = (ctxWidth  / 2) - (newWidth  / 2),
        offsetY     = (ctxHeight / 2) - (newHeight / 2);
    ctx.clearRect(0, 0, ctxWidth, ctxHeight);
    ctx.drawImage(this, offsetX, offsetY, newWidth, newHeight);
  };

  imageObj.src = url;
}
#image-viewer {
  background-color: #E4E4E4;
  background-image:
    linear-gradient(45deg, #7F7F7F 25%, transparent 25%, transparent 75%, #7F7F7F 75%, #7F7F7F), 
    linear-gradient(45deg, #7F7F7F 25%, transparent 25%, transparent 75%, #7F7F7F 75%, #7F7F7F);
  background-size: 20px 20px;
  background-position: 0 0, 30px 30px
}
<canvas id="image-viewer" width="1280" height="960"></canvas>

答案 1 :(得分:0)

这是一个解决方案。基本上它主要是css,但我们使用JS来获取图像尺寸。如果任一维度大于我们的边界(x> 960或y> 1280),则设置css propeprty background-size:contain

    var onload = function () {
//grab image dimensions on load
        var w = this.width;
        var h = this.height;
        if (w > 960 || h > 1280) {
//set contain if needed
            document.getElementById(this.dataset.div)
                    .style.backgroundSize = "contain";
        }
    };
//grab all the container divs
    var divs = document.querySelectorAll('.container');
//iterate thru them
    for (i = 0; i < divs.length; i++) {
        var div = divs[i];
        var img = new Image;
//set the id of the current div as a data attribute of the img, 
//so we can reference it in the onload function
        img.dataset.div = div.id;
//apply onload function
        img.onload = onload;
//set the img src to the background image. use a quick regex to extract 
//just the img url from the whole "url(img.ext)" string
        img.src = getComputedStyle(div, 0).backgroundImage
                .match(/url\(['"]?([a-z0-9\/:.]+)['"]{0,1}/i)[1];
    }
div.container{
width:960px;
height:1280px;
border:1px solid black;
background-position:center;
background-repeat:no-repeat;
background-color:transparent;
/*background-image:url(/path/to/img.ext);*/
}
div#container-1{
background-image:url(http://i.imgur.com/5PF0Xdi.jpg);
}
div#container-2{
background-image:url(http://i.imgur.com/po0fJFT.png);
}
div#container-3{
background-image:url(http://i.imgur.com/Ijzdt0o.png);
}
<div class="container" id="container-1"></div>
<div class="container" id="container-2"></div>
<div class="container" id="container-3"></div>