A canvas has two sizes, the internal and the external: the internal one indicates the pixels with which you are going to work in the calculations, the external one indicates the pixels of the canvas element in the HTML:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'green';
ctx.fillRect(10, 10, 100, 100);
var canvas2 = document.getElementById('canvas2');
var ctx2 = canvas2.getContext('2d');
ctx2.fillStyle = 'green';
ctx2.fillRect(10, 10, 100, 100);
console.log('Tamaño 'externo': (${canvas.scrollWidth},${canvas.scrollHeight})');
console.log('Tamaño 'interno': (${canvas.width},${canvas.height})');
canvas {
background-color: gray;
float:left;
}
#canvas {
width: 100px;
height: 50px;
}
<canvas width="150" height="140" id="canvas"></canvas>
<canvas width="200" height="200" id="canvas2"></canvas>
As you can see, in both "canvas" a square of 90 * 90 is drawn, but the first one is totally deformed. You can calculate the deformation ratio using both the external and the internal measures, and therefore calculate the "visible" size of the square on any axis.
On the other hand, the pixels used by CSS and the actual pixels on your screen may not match because of the pixel density issue: On a 24-inch monitor with a resolution of 1920 * 1080, one pixel may be medium millimeter, while in a mobile it may be that there are 15 pixels per millimeter.
Therefore, it is recommended that the "internal" size of the canvas be equal to the external size (assuming you want to keep the proportions) multiplied by the window.devicePixelRatio
property, so that what you show on the canvas looks as good as possible. This does not give an exact result, because most mobiles give you a value of 2 or 3 (usually a whole value) when perhaps the correct thing would be something like 2.56 or a similar value.
By definition , a "CSS pixel" has a size such that 96px = 1in (one inch, 25.4 mm).
Finally, I remind you that if you are going to print from the browser, the screen CSS does not have to be the same as the printer's: using @media print
in your styles you can define a presentation for the print other than the of the screen, defining the size of your image to adjust it to your liking.