【问题标题】:How to scale game viewport?如何缩放游戏视口?
【发布时间】:2017-02-03 07:29:20
【问题描述】:

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

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

【问题讨论】:

标签: javascript css html math


【解决方案1】:

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

【讨论】:

  • 但是如何缩放容器的对象、场景对象?
【解决方案2】:

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

【讨论】:

  • 这个游戏我不使用画布,只有 CSS。如何将所有内容缩放到适当的分辨率?感谢您顺便回答:)
  • 天哪,缩放 html 游戏?我想我不会给任何固定宽度的东西。给它一个百分比。如果这不起作用,您可能需要使用 javascript
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-09
  • 1970-01-01
相关资源
最近更新 更多