js转换px与mm, cm

博客主要展示了使用JS进行毫米与像素转换及DPI计算的代码。包含compute函数用于获取纸张宽高并转换为像素,cm2px函数根据毫米计算DPI,getDPI函数获取设备DPI,实现了毫米到像素的转换及DPI的计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

纸张宽度(毫米mm):

纸张宽度(毫米cm):






function compute(t){
var width=document.getElementById(“width”).value;
var height=document.getElementById(“height”).value;
console.log(“width:”+width)
console.log(“height:”+height)
var width_px=cm2px(width);
var height_px=cm2px(height);
console.log(“width_px:”+width_px)
console.log(“height:”+height)
document.getElementById(“width_px”).innerHTML=width_px+" px";
document.getElementById(“height_px”).innerHTML=height_px+" px";
if(t==2){
var tmpNode = document.createElement(“DIV”);
tmpNode.setAttribute(‘style’, ‘width:’+width_px+‘px;height:’+height_px+‘px;border:solid 1px #000;text-align:center’);
tmpNode.innerHTML=width+""+height+"("+width_px+""+height_px+")";
document.getElementById(“testDiv”).appendChild(tmpNode);
}else{
document.getElementById(“testDiv1”).setAttribute(‘style’, ‘width:’+width_px+‘px;height:’+height_px+‘px;border:solid 1px #000’);
}

}
//根据毫米算DPI
function cm2px(cm) {
var dpi = getDPI();
var pixel = parseFloat(cm) / 25.4 * dpi[0]; //只计算x轴的dPI
return (parseInt(pixel))
}

function getDPI() {
var arrDPI = new Array();
if (window.screen.deviceXDPI != undefined) {//ie 9
arrDPI[0] = window.screen.deviceXDPI;
arrDPI[1] = window.screen.deviceYDPI;
}else {//chrome firefox
var tmpNode = document.createElement(“DIV”);
tmpNode.style.cssText = “width:1in;height:1in;position:absolute;left:0px;top:0px;z-index:99;visibility:hidden”;
document.body.appendChild(tmpNode);
arrDPI[0] = parseInt(tmpNode.offsetWidth);
arrDPI[1] = parseInt(tmpNode.offsetHeight);
tmpNode.parentNode.removeChild(tmpNode);

}
return arrDPI;
}
console.log(“dpi:”+getDPI());

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值