【问题标题】:How to scale (resize) image keep aspect ratio in javascript如何在javascript中缩放(调整大小)图像保持纵横比
【发布时间】:2017-02-08 23:51:05
【问题描述】:

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

  • 如果图像比预期尺寸大,它会按比例缩小(保持纵横比)并且空白区域用透明颜色填充。
  • 如果图像小于预期尺寸,则它不缩放而是居中,空白区域用透明颜色填充。

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

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

更新:这里的工作解决方案,非常感谢@Mr。多旋风 Update solution

【问题讨论】:

  • 我使用了这种方法并进行了一些更改以将图像大小调整为完全预期的尺寸,但它使图像失去了比例:link
  • 欢迎来到 SO。请访问help center 了解询问内容和方式。提示:在minimal reproducible example 中发布工作和代码
  • 感谢提醒
  • 您提供的链接的哪一部分失败了?
  • 我会尝试 Jason Nathan 的回答 #2

标签: javascript


【解决方案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>

【讨论】:

  • 谢谢,我会试试你的解决方案
【解决方案2】:

这里有一个解决方案。基本上它主要是 css,但我们使用 JS 来获取图像尺寸。如果任一维度大于我们的界限(x>960 或 y>1280),则设置 css 属性 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>  

【讨论】:

    猜你喜欢
    • 2013-06-26
    • 2012-04-15
    • 2012-05-01
    • 2012-11-15
    • 2019-08-15
    相关资源
    最近更新 更多