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?