gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 04:29:48 25 4
gpt4 key购买 nike

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

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

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

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

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

最佳答案

为了确定用于缩放的宽高比,您需要确定哪个维度更大。这样做的一种方法是,您只需将图像的宽度/高度除以观看者的宽度/高度,这就可以确定比例因子。

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

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>

关于javascript - 如何在javascript中缩放(调整大小)图像保持纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39790874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com