如何使 PIXI 渲染器适应浏览器的宽度和高度?

How to fit PIXI renderer into browser width and height?

我正在开发一个嵌入 Wordpress 首页的文字游戏,它使用 PIXI.js 绘制游戏板及其上方和下方 - 按钮和选择菜单等少数 jQuery 元素。

虽然我进展顺利,但有一个问题我不知道如何解决,想知道其他 PIXI 开发人员如何解决它 - 硬编码 canvas 大小(我已将其设置为 1020 x 1080)对于某些浏览器来说太大了。

例如,我的 Macbook Air 上有 2 Google Chrome 个屏幕截图:

此外,我打算将我的游戏嵌入 Facebook Canvas,这将使屏幕资产更加稀缺。

这是我的 JavaScript 代码的摘录,请问如何改进它?

    var renderer = new PIXI.autoDetectRenderer(1020, 1020 + 60, { 
            view: document.getElementById('board')
    });
    renderer.view.style.padding = '4px';
    renderer.backgroundColor = 0xFFFFFF;

    var charm = new Charm(PIXI);

    var stage = new PIXI.Sprite();
    stage.interactive = true;
    stage
            .on('mousedown',  onDragStart)
            .on('touchstart', onDragStart)
            .on('mousemove', onDragMove)
            .on('touchmove', onDragMove)
            .on('mouseup',         onDragEnd)
            .on('mouseupoutside',  onDragEnd)
            .on('touchend',        onDragEnd)
            .on('touchendoutside', onDragEnd);

使用 window.innerWidthwindow.innerHeight 使您的 board 元素尺寸最佳。

我的解决方案如下所示(仅使用原始 canvas,没有框架)

var context = document.getElementById('game');
function gameResize()
    {
    if (window.innerWidth/window.innerHeight > 1280/720)
        {
        context.height = window.innerHeight;
        context.width = 1280*context.height/720;
        }
    else
        {
        context.width = window.innerWidth;
        context.height = 720*context.width/1280;
        }
    }

你也可以直接改变board大小,用PIXI renderer.resize(),但我不确定哪个更正确。

renderer.resize(),但不缩放游戏板

用户名:

renderer.view.style.width  = ...... + 'px';
renderer.view.style.height = ...... + 'px';

效果很好,可以缩放内容。

此外,我发现 jQuery resizable 与 PIXI 配合得很好:

$('#board').resizable({
       aspectRatio: 1020 / (1020 + 60),
       minWidth: 1020 / 2
});