I would like to fill a div with an image (but not stretch) just like in this post CSS Image size, how to fill, not stretch? but instead of using CSS I need to calculate values using JavaScript.
This is what I have:
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
is the div and image
is a normal Image().
It works in most cases but not when for example this._width < ratio*this._height
.
How can I get the algorithm to work for all cases? I know it's pretty simple but I can't get it to work.