0

I wish to use javascript to render a bitmap in a canvas at screen resolution, whatever the zoom level. Is there a way to do it?

I found a similar unanswered question there: How to get size of an element in physical pixels?

I noticed that html pixels match physical pixels at the default zoom level in Firefox on my desktop. But if I zoom in or out, then they don't match any more. Is there a way to know the zoom level?

Edit: here is my best attempt so far. It does not work with Chrome on Android:

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
 </head>
 <body>
  <p id="myp"></p>
  <p id="resize"></p>
  <canvas id="canvas" width="1" height="1" style="width:50%"></canvas>

  <script type="text/javascript">
   function reDraw(id)
   {
    canvas = document.getElementById(id);
    rect = canvas.getBoundingClientRect();
    size = Math.round((rect.right - rect.left) * window.devicePixelRatio);

    canvas.width = size
    canvas.height = size

    context = canvas.getContext("2d");
    imageData = context.createImageData(size, size);

    for (i = 0; i < size * size; i++)
    {
     j = (i / size) + (i % size);
     imageData.data[4 * i + 0] = 255*(j & 1);
     imageData.data[4 * i + 1] = 255*(j & 1);
     imageData.data[4 * i + 2] = 255*(j & 1);
     imageData.data[4 * i + 3] = 255;
    }

    context.putImageData(imageData, 0, 0);
    document.getElementById("myp").innerHTML =
     "devicePixelRatio = " + window.devicePixelRatio + "; bitmap size = " + size;
   }

   var x = 0;
   function refresh()
   {
    x += 1;
    document.getElementById("resize").innerHTML = "resize counter: " + x;
    reDraw("canvas");
   }

   window.addEventListener('resize', refresh);

   refresh()

  </script>

 </body>
</html>
Community
  • 1
  • 1
Rémi
  • 3,705
  • 1
  • 28
  • 39
  • how does your question differ from the one you've linked to? If you don't like the answer you should [add a bounty](http://stackoverflow.com/help/privileges/set-bounties) not create a duplicate – Liam Jul 19 '16 at 10:42
  • Possible duplicate of [How to get size of an element in physical pixels?](http://stackoverflow.com/questions/17267620/how-to-get-size-of-an-element-in-physical-pixels) – Liam Jul 19 '16 at 10:44
  • 1
    there's also this [How to detect page zoom level in all modern browsers?](http://stackoverflow.com/questions/1713771/how-to-detect-page-zoom-level-in-all-modern-browsers) which is linked in that question – Liam Jul 19 '16 at 10:46

1 Answers1

1

window.devicePixelRatio returns a ratio of physical pixels to CSS pixels. On desktop this will usually be the zoom level, on mobile devices it is approximately a ratio of device resolution to 96dpi but it varies highly between the vendors.

Andrew Sklyarevsky
  • 2,095
  • 14
  • 17
  • Thanks. This helped. Unfortunately, it does not work with Chrome on Android. I will add my sample javascript to the question. I hope someone will be able to help more. – Rémi Jul 19 '16 at 12:31