缩小图像以适合div [英] Scale down image to fit div
问题描述
我正在尝试按比例缩小一个装料,以适合一个大于最大宽度和高度设置的div容器.我下面的代码获取图像的宽度和高度以及允许的最大尺寸设置.
I am trying to scale down an inage to fit a div container that are greater then the max width and heights set. I have the code below that gets the width and height of the image and the sets max sizes allowed.
这是我无法进入的深度,它在下面加载的图像为662x599.宽度大于允许的最大值,因此我需要将其正确缩小并放置在div的中心.
This is were I'm out of my depth, the image it loads below is 662x599. The width is greater the the max allowed so I need it to scale down correctly and be placed into the center of the div.
var max_width = 713;
var max_height = 550;
var img = new Image();
img.onload = function() {
img.width = this.width;
img.height = this.height;
}
img.src = 'files.jpg';
下面是我手动调整图像大小的示例,它看起来不错,可以为您提供一个粗略的外观示例.我打算使用样式"top"和"left"将图像放置在div的中心.
Below is an example me resizing the image manually that looks good to give you a rough example of how it should look should. I intent to use styles "top" and "left" to place the image in the center of the div.
<img style="width: 613px; height: 550px; top: 0px; left: 50px;" src="files.jpg">
任何帮助都将非常感谢.
Any help would be great thanks.
推荐答案
这是用于计算width
,height
,top
,left
的代码.
This is code to calculate width
, height
, top
, left
.
// max_width = 713
// max_height = 550
// img.width = 662
// img.height = 599
scale_width = max_width / img.width;
scale_height = max_height / img.height;
scale = Math.min(scale_width, scale_height);
width = img.width * scale; // 608
height = img.height * scale; // 550
left = (max_width - width)/2; // 52
top = (max_height - height)/2; // 0
这篇关于缩小图像以适合div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!