Search code examples
javascriptscreenresolutionscreen-resolutiondpi

Always the same size of image on all screens


I need that square image always be the same size on any screen (including mobile, tablet...). So if I take the ruler and measure image on any screen it have to be 5mm for example. It must be in JavaScript.

I wonder if the size of that image depends only of screen's DPI or it depends of screen resolution also? If in JavaScript I detect screen's DPI (and resolution if needed) is there any formula (or some JavaScript function) to calculate image size to get always the same result?

In the end, can I define image size in some unit which will ensure image to be always the same?

I asked the question here because it is connected to JavaScript, if you think that it is more suitable for some other forum please let me know.

Thanks...


Solution

  • If I understand correctly you want an image always to have a fixed absolute physical size. There is no way to achieve that. You can define a width with absolute units like inch, centimeter or millimeter, but the rendered result differs from one screen to another.

    Every browser has set internally 1 inch = 96px, and with that base all other units are calculated. So only if a screen has a physical pixel-size of exactly 25.4 / 96 = 0.26458 mm an element having width set to 5mm is really 5mm.

    But the absolute physical size of a pixel differs widely on different screens and is not detectable by javascript.

    EDIT According to your comment: Yes it is possible with your own screen. You can display an element with a width set to 200mm and measure the real width on screen in mm with a ruler. The quotient 200 / your_measurement gives you a conversion factor.

    If you now want to set a width to a fixed value you have to multiply that value with the factor.

    Display following file and measure the width of the red quadrat:

    <!doctype html>
        <head>
            <style>
                div {width: 200mm; height: 200mm; margin: 50px; background-color: red;}
            </style>
        </head>
        <body>
            <div></div>
        </body>
    </html>
    

    The conversion factor is valid for all absolute units you want to use.

    With some interaction of a user you can calibrate a users screen as they did on the ZEISS page you linked to. The user has to compare the element on screen against a fixed width (e.g. width of a credit card = 54mm). Since here the user is fixed and the code does the measurement, calculation of the factor is contrariwise: conversion factor f = code_result / 54.

    I have made a FIDDLE here with 0.5mm-steps to get more accuracy.