我想用图像填充 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
时则无效。 .
如何让算法适用于所有情况?我知道这很简单,但我无法让它发挥作用。
最佳答案
我认为问题在于您将 ratio
与 1
进行比较,但您应该将其与 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/