Skip to content

Instantly share code, notes, and snippets.

@shpaker
Created July 9, 2021 06:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shpaker/d6acc7e0afa0999bda0b8e1821c91c58 to your computer and use it in GitHub Desktop.
Save shpaker/d6acc7e0afa0999bda0b8e1821c91c58 to your computer and use it in GitHub Desktop.
Detect the dpi/dpcm/dpmm in your browser
// var dp = new dpLib();
// alert(
// "7 in = " + dp.i(7) + " px \n" +
// "16 cm = " + dp.cm(16) + " px \n" +
// "6 in = " + dp.i2cm(6) + " cm \n" +
// "15 cm = " + dp.cm2i(15) + " in \n"
// );
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