Skip to content

Instantly share code, notes, and snippets.

@shpaker
Created December 7, 2017 10:31
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save shpaker/0af8058253e08d0f531dec8ac1eeb13b to your computer and use it in GitHub Desktop.
// Calc DPI with JS
function dpLib(debug) {
"use strict";
var div = document.createElement("div");
div.style.width = "1in";
div.style.position = "abolute";
div.style.top = "-100%";
div.style.bottom = "-100%";
document.body.appendChild(div);
//
this.version = "1.0";
this.cmInInch = 2.54; // 1 in = 2.54 cm
this.pixInInch = div.offsetWidth;
this.pixInCm = this.pixInInch / this.cmInInch;
//
document.body.removeChild(div);
if (debug) {
console.info("Version of dpLib: %s", this.version);
console.info("inch = %s pixels \n centimetr = %s pixels", this.pixInInch, this.pixInCm);
}
}
// inches
dpLib.prototype.i = function (i) {
if (!i) i = 1;
return this.pixInInch * i;
}
// centimetres
dpLib.prototype.cm = function (cm) {
if (!cm) cm = 1;
return this.pixInCm * cm;
}
// convert centimetres to inches
dpLib.prototype.cm2i = function (cm) {
if (!cm) cm = 1;
return cm / this.cmInInch;
}
// convert inches to centimetres
dpLib.prototype.i2cm = function (i) {
if (!i) i = 1;
return i * this.cmInInch;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment