天天看點

px和毫米的換算_js轉換px與mm, cm

紙張寬度(毫米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());