我的目标是创建一个javascript游戏,利用在canvas元素上移动和渲染精灵和图像。我想确保在不同的窗口分辨率下游戏“伸展”以填充窗口而不会影响任何机制。
我通过使用以下代码实现了这一目标:
<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>
这使得画布精灵总是以固定的分辨率被操纵/渲染,我已经定义为1920x1080,但是元素可以缩小或拉伸以适应其他分辨率。
如果我在代码中包含Doctype行,它不起作用,这使我认为这是旧代码,我可以以更好的方式执行此操作。有什么建议吗?