如何扩展游戏视口?

时间:2016-09-26 04:12:09

标签: javascript css html5 math

我使用HTML5 / CSS / JS制作游戏。现在我遇到了无法解决的问题。 如何将游戏扩展到任何屏幕分辨率?也许它很简单,但不适合我。

解决

var RATIO = 480 / 800; // Original ratio.
function resize() {
    var DEVICE_WIDTH = window.innerWidth,
        DEVICE_HEIGHT = window.innerHeight,
        ratio = DEVICE_WIDTH / DEVICE_HEIGHT,
        scale = 1;
    // If window changes by height we calculate scale parameter fo width
    if (ratio > RATIO) { 
        scale = DEVICE_HEIGHT / 800; // Devide by original viewport height
    } else { // If window changes by width we calculate scale parameter for height
        scale = DEVICE_WIDTH / 480; // Devide by original viewport width
    }
}

// So, now you can continue make your game, but in draw method you have to multiply 
// everything by this scale parameter (x and y coords, width and height)

希望它能帮助像我这样的人:)

2 个答案:

答案 0 :(得分:0)

假设您已将您的画布命名为canvas。在不拉伸的情况下更改其大小的代码如下:

function setSize(width, height)
{
    canvas.width = width; 
    canvas.style.width = width + "px";
    canvas.height = height; 
    canvas.style.height = height + "px";
}

//And then to use that,
setSize(350, 200);

答案 1 :(得分:0)

您可以根据需要动态设置它,例如。如果你的容器有一些id或类,你可以

var container = document.getElementById(idName);

var resize = function(element) {
    return function (width, height) {
          element.style.width = width;
          element.style.height = height;
     }
}

var sizeListener = resize(container)(document.documentElement.clientWidth,document.documentElement.clientHeight);