我有两个盒子/电视。一个外盒子和一个内盒子。内盒始终包含在外盒内。提供以下信息:
外盒: width=200 height=100
内箱:纵横比=16/9
在JavaScript中,如何计算内部框的最大大小以保持其纵横比?
发布于 2022-07-27 19:58:41
获取外部长宽比,并使用它来确定内箱是否需要相对于外框而言是字母框(景观,较短)还是柱盒(纵向,窄)。在此基础上计算内部尺寸。您还可以计算中心所需的偏移量。
const outerWidth = 200;
const outerHeight = 100;
const aspectRatio = 16/9;
let innerWidth, innerHeight, innerTop, innerLeft;
if (outerWidth / outerHeight > aspectRatio) {
innerWidth = outerHeight * aspectRatio;
innerHeight = outerHeight;
innerLeft = (outerWidth - innerWidth) / 2;
innerTop = 0;
} else {
innerWidth = outerWidth;
innerHeight = outerWidth / aspectRatio;
innerLeft = 0;
innerTop = (outerHeight - innerHeight) / 2;
}发布于 2022-07-27 19:51:00
我知道您是专门要求JavaScript的,但是这是非常好的 simple to do in CSS with aspect-ratio,如果您需要JS中的维度,您可以只获取呈现的维度。
const pre = document.querySelector('pre');
const aspect = document.querySelector('.ratio');
// getboundingClientRect also works.
const dimensions = window.getComputedStyle(aspect);
pre.textContent = `width: ${dimensions.width}, height: ${dimensions.height}`;.container {
width: 200px;
height: 100px;
}
.ratio {
aspect-ratio: 16 / 9;
/* Just keeping it within the constaints */
max-height: 100px;
border: 1px solid red;
}
.no-ratio {
border: 1px solid red;
}<div class="container">
<div class="ratio">
16:9
</div>
</div>
<pre></pre>
<div class="container">
<div class="no-ratio">
Not 16:9.
</div>
</div>
<pre></pre>
发布于 2022-07-27 19:40:35
let outerBoxWidth = 200;
let outerBoxHeight = 100;
let maxInnerBoxWidth = ((outerBoxWidth / 16) | 0);
let maxInnerBoxHeight = ((outerBoxHeight / 9) | 0);
let widthLower = maxInnerBoxHeight > maxInnerBoxWidth;
if(widthLower){
let innerBoxHeight = 9 * maxInnerBoxWidth;
let innerBoxWidth = 17 * maxInnerBoxWidth;
}else{
let innerBoxHeight = 9 * maxInnerBoxHeight;
let innerBoxWidth = 17 * maxInnerBoxHeight;
}https://stackoverflow.com/questions/73143651
复制相似问题