- 我有一个外部div,其分配的宽度/高度以毫米为单位(mm只是分配的值,不用于渲染)。
- 在里面,我还有另一个div,其实际宽度/高度为 px。
- 两个div 可以有不同的比率。
我想做的是使用 JavaScript 计算内部div 宽度/高度(以毫米为单位),并考虑比例。
示例 1:分配的外部div 宽度/高度为 30x30mm,比例为 0.8,内部div 宽度/高度(以 px 为单位)为 600x600 像素,结果应为 24x24mm。
示例 2:分配的外部div 宽度/高度为 60x30mm,比例为 1.0,内部div 宽度/高度(以 px 为单位)为 300x600 像素,结果应为 15x30mm。
外部div 宽度/高度(以毫米为单位)被视为最大尺寸。
猜猜这很容易,但div/表面可以有不同的比例这一事实对我来说很复杂。
var calcDimensions = function(scale) {
var surfaceWidth, surfaceHeight, contentWidth, contentHeight, contentRatio, surfaceRatio;
// Output variable holding the result
var dimensions = { width: 0, height: 0 };
surfaceWidth = 30; // outer divs assigned width in mm
surfaceHeight = 14; // outer divs assigned height in mm
contentWidth = 600; // inner divs real width in px
contentHeight = 196; // inner divs real height in px
scale = 0.8; // Can have a value between 0.1 - 1.0
contentRatio = contentWidth > contentHeight ? contentHeight / contentWidth : contentWidth / contentHeight; // Assuming this is needed in the calculation.
surfaceRatio = surfaceWidth > surfaceHeight ? surfaceHeight / surfaceWidth : surfaceWidth / surfaceHeight; // Assuming this is needed in the calculation.
// Calculate stuff here and return calculated dimensions
return dimensions;
}
您可以尝试执行以下操作:
在视图中添加一个宽度 = 100mm 的div
<div style="width:100mm;height:0" id="measure">
也许您必须设置 z 索引或 bg 颜色才能使div 不可见。现在,您可以像这样计算设备上每毫米的像素数:
let pxPerMm = document.getElementById('measure').offsetWidth / 100;