全出血图像调整大小计算
我正在尝试编写一个 JavaScript 函数,该函数将始终扩展图像以填充 div(因此根据需要裁剪顶部或侧面)。它是 CSS3 代码 background-size: cover 的 JavaScript 等效项。
我这辈子都无法弄清楚。这就是我到目前为止所得到的:
function full_bleed(box_width, box_height, new_width, new_height)
{
var aspect_ratio=new_width/new_height;
if(new_height<box_height) {
new_height=box_height;
new_width=Math.round(new_height*aspect_ratio);
}
if(new_width<box_width) {
new_width=box_width;
new_height=Math.round(new_width/aspect_ratio);
}
return {
width: new_width,
height: new_height
};
}
我想你们中的一个人可能已经有了这个方程。
I am trying to write a JavaScript function that will expand an image to fill a div always (so crop top or sides as needed). It is the JavaScript equivalent of the CSS3 code background-size: cover.
I can't for the life of me figure it out. This is what I have so far:
function full_bleed(box_width, box_height, new_width, new_height)
{
var aspect_ratio=new_width/new_height;
if(new_height<box_height) {
new_height=box_height;
new_width=Math.round(new_height*aspect_ratio);
}
if(new_width<box_width) {
new_width=box_width;
new_height=Math.round(new_width/aspect_ratio);
}
return {
width: new_width,
height: new_height
};
}
I figured one of you guys might have the equation lying around.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
感谢本的评论,我明白了。
Thanks to the comment from Ben, I figured it out.
我对德鲁的解决方案做了一些更改,以更好地满足我的需求。
想法是相同的,但这里的要点是在没有媒体初始尺寸的情况下计算放大的尺寸,而不是使用给定的宽高比。我将它用于视频嵌入,而不是图像,例如,我通过 YouTube API 加载视频,并且我没有任何初始大小,但我知道比率,并且我想在可用空间上拉伸视频。 (当然,也可以改回来,根据视频或图片的实际尺寸来计算比例。)
还做了一些代码简化。
I made some changes on Drew's solution to better fit my needs.
The idea is the same, but the point here is to calculate the scaled up size without having an initial size of the media, instead using a given aspect ratio. I use it for video embeds, rather than images, where I load the video via YouTube API, for example, and I don't have any initial size, but I know the ratio and I want to stretch the video across the available space. (Of course, it can be changed back to calculate the ratio from the actual dimensions of the video or image.)
Also made some code simplifications.