javascript - 使用 JavaScript 填充图像(而非拉伸(stretch))

标签 javascript

我想用图像填充 div(但不拉伸(stretch)),就像这篇文章 CSS Image size, how to fill, not stretch? 中那样但我需要使用 JavaScript 来计算值,而不是使用 CSS。

这就是我所拥有的:

image.onload = ()=> {
      var ratio: number = image.width / image.height;

      if (ratio > 1) {
        image.height = this._height;
        image.width = ratio * this._height;
        image.style.left = -((image.width - this._width) / 2) + "px";
      } else {
        ratio = 1 / ratio;
        image.width = this._width;
        image.height = ratio * this._width;
        image.style.top = -((image.height - this._height) / 2) + "px";
      }
    };

this是 div 和 image是一个普通的 Image()。

它在大多数情况下都有效,但在例如 this._width < ratio*this._height 时则无效。 .

如何让算法适用于所有情况?我知道这很简单,但我无法让它发挥作用。

最佳答案

我认为问题在于您将 ratio1 进行比较,但您应该将其与 div 的比率进行比较:

image.onload = ()=> {
      var imgRatio: number = image.width / image.height,
          divRatio: number = this._width / this._height;

      if (imgRatio > divRatio) {
        image.height = this._height;
        image.width = this._height * imgRatio;
        image.style.left = -((image.width - this._width) / 2) + "px";
      } else {
        image.width = this._width;
        image.height = this._width / imgRatio;
        image.style.top = -((image.height - this._height) / 2) + "px";
      }
};

关于javascript - 使用 JavaScript 填充图像(而非拉伸(stretch)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22485752/

相关文章:

javascript - WinJS.Promise 无法正常工作

javascript - 在javascript中反向按位移位

javascript - 删除功能不起作用angularjs

javascript - 如何向使用 D3.js 创建的 map 添加或创建 map 比例尺

javascript - 如何在每个时间段检测到最大条目时更改日历覆盖

javascript - Angular 中的动态选择元素过滤

javascript - 从 facebook graph API 获取全尺寸图片

javascript - 允许保存新项目并在 SharePoint NewForm.aspx 中继续

javascript - for 循环将多个值推送到数组中

Javascript 交换图像