0

My objective is to create a javascript game that makes use of moving and rendering sprites and images on a canvas element. I want to make sure that across different window resolutions the game "stretches" to fill the window without compromising any mechanic.

I've been achieving this by using the following code:

<canvas id="myCanvas" width=1920 height=1080>
</canvas>                                                                                    


<script>

   var viewportwidth;
   var viewportheight;

   //(mozilla/netscape/opera/IE7) 
   if (typeof window.innerWidth != 'undefined')
   {
       viewportwidth = window.innerWidth,
       viewportheight = window.innerHeight
   }



   // IE6 
   else if (typeof document.documentElement != 'undefined'
   && typeof document.documentElement.clientWidth !=
   'undefined' && document.documentElement.clientWidth != 0)
   {
       viewportwidth = document.documentElement.clientWidth,
       viewportheight = document.documentElement.clientHeight
   }


   // older versions of IE
   else
   {
       viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
       viewportheight = document.getElementsByTagName('body')[0].clientHeight
   }
   myCanvas.style.height=viewportheight;
   myCanvas.style.width=viewportwidth;

</script>

This makes it so that the canvas sprites are always being manipulated/rendered at a fixed resolution which I have defined to be 1920x1080, but the element can be shrunk or stretched to fit in other resolutions.

It doesn't work if I include a Doctype line in the code, which leads me to think this is old code and I could be doing this in a much better way. Any suggestions?

Hugo Lobo
  • 1
  • 1
  • Yes, you could adjust the size of the canvas based on viewport size (http://stackoverflow.com/questions/1664785/resize-html5-canvas-to-fit-window), but then the game itself would have to adjust everything it's drawing inside the canvas to the new size. It's not vectors, it can't abstract actual pixel sizes. – Sergiu Paraschiv Feb 29 '16 at 18:58
  • Which means I would have to calculate everything using relative values, right? – Hugo Lobo Feb 29 '16 at 19:02
  • Yes. There is another solution though, involving CSS transforms, but it distorts the canvas and the "pixels" themselves. – Sergiu Paraschiv Feb 29 '16 at 19:14
  • Check out karaxuna's answer on this previous [post](http://stackoverflow.com/questions/15878377/html5-responsive-canvas-resizing-the-browser-canvas-draw-disappear/23128583#23128583). It scales using CSS and (importantly!) does proportional scaling so the canvas content is not distorted. – markE Feb 29 '16 at 22:34

0 Answers0