如何缩放游戏视窗

How to scale game viewport?

本文关键字:游戏 缩放 何缩放      更新时间:2023-09-26

我使用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)

希望它能帮助到像我这样的人。

假设您已经将画布命名为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);

您可以根据需要动态设置它。如果你的容器有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);