Javascript图像调整大小

Kom*_*ang 45 javascript image-manipulation internet-explorer-6

有谁知道如何使用JavaScript按比例调整图像大小?

我试图通过添加属性height和动态修改DOM width,但似乎在IE6上不起作用.

Dan*_*Dan 66

要按比例修改图像,只需更改宽度/高度css属性中的一个,将另一个设置保留为自动.

image.style.width = '50%'
image.style.height = 'auto'
Run Code Online (Sandbox Code Playgroud)

这将确保其纵横比保持不变.

请记住,浏览器往往会在很好地调整图像大小-你可能会发现你的调整后的图像看起来可怕.


Kom*_*ang 18

好吧,它解决了,这是我的最终代码

if($(this).width() > $(this).height()) { 
 $(this).css('width',MaxPreviewDimension+'px');
 $(this).css('height','auto');
} else {
 $(this).css('height',MaxPreviewDimension+'px');
 $(this).css('width','auto');
}
Run Code Online (Sandbox Code Playgroud)

多谢你们

  • `var target = $(this); if (target.width() > target.height()) target.css({ "width": MaxPreviewDimension + "px", "height": "auto" }); else target.css({ "height": MaxPreviewDimension + "px", "width": auto })` (2认同)

Nea*_*all 5

不要修改图像的高度和宽度属性,而是尝试修改CSS高度和宽度.

myimg = document.getElementById('myimg');
myimg.style.height = "50px";
myimg.style.width = "50px";
Run Code Online (Sandbox Code Playgroud)

一个常见的"问题"是高度和宽度样式是包含单位的字符串,如上例中的"px".

编辑 - 我认为直接设置高度和宽度而不是使用style.height和style.width应该工作.它还具有已经具有原始尺寸的优点.你可以发布一些代码吗?你确定你处于标准模式而不是怪癖模式吗?

这应该工作:

myimg = document.getElementById('myimg');
myimg.height = myimg.height * 2;
myimg.width = myimg.width * 2;
Run Code Online (Sandbox Code Playgroud)


Jas*_*han 5

我在这里回答了这个问题:如何按比例调整图像大小/保持纵横比?.我在这里复制它,因为我真的认为这是一个非常可靠的方法:)

 /**
  * Conserve aspect ratio of the original region. Useful when shrinking/enlarging
  * images to fit into a certain area.
  *
  * @param {Number} srcWidth width of source image
  * @param {Number} srcHeight height of source image
  * @param {Number} maxWidth maximum available width
  * @param {Number} maxHeight maximum available height
  * @return {Object} { width, height }
  */
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {

    var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);

    return { width: srcWidth*ratio, height: srcHeight*ratio };
 }
Run Code Online (Sandbox Code Playgroud)