让JavaScript Canvas游戏响应CSS3

Make JavaScript Canvas Game Responsive with CSS3

本文关键字:响应 CSS3 游戏 Canvas JavaScript      更新时间:2023-09-26

我有一个HTML画布游戏,我想通过使用CSS3设置其宽度和高度来做出响应。

JS画布游戏的代码是:
    <div id="main">
        <div class="game-box">
             <div class="game-container">
                  <div id="phaser-div">
                  </div>
             </div><!-- end game-container -->
        </div><!-- end game-box -->

    <script src="js/jquery-1.11.2.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/phaser.min.js"></script>
    <script>
        var game = new Phaser.Game(832, 508, Phaser.WEBGL, 'phaser-div', { preload: preload, create: create, update: update });
var background;
var filter;
function preload() {
    var urlBase = location.href.substring(0, location.href.lastIndexOf("/") + 1);
    game.load.image('phaser', urlBase + 'games/game001/game001-logo.png');
    game.load.script('filter', urlBase + 'games/game001/marble.js');
    this.game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; this.game.scale.setShowAll(); window.addEventListener('resize', function () { this.game.scale.refresh(); }); this.game.scale.refresh();
}
function create() {
    var logo = game.add.sprite(game.world.centerX, game.world.centerY, 'phaser');
    logo.anchor.setTo(0.5, 0.5);
    background = game.add.sprite(0, 0);
    background.width = 832;
    background.height = 508;
    filter = game.add.filter('Marble', 832, 508);
    filter.alpha = 0.2;
    //  The following properties are available (shown at default values)
    //  filter.speed = 10.0;
    //  filter.intensity = 0.30;
    background.filters = [filter];
}
function update() {
    filter.update();
}
    </script>

Live Link:
http://revolutionarydeveloper.com/project-games/index.html

我试着设置像#phaser-div canvas {width: 100%;Height: 470px;}但似乎不起作用。如何使用CSS3使其响应并使用媒体查询修改宽度和高度?

多谢

注:本游戏使用了Phaser.JS。包括它的链接,以防它是相关的。
https://cdn.jsdelivr.net/phaser/2.6.2/phaser.js

phaser有自己的代码来让游戏响应

Phaser.ScaleManager.SHOW_ALL;

查看http://phaser.io/news/2015/02/responsive-games-basics

Phaser method
this.time.events.add(200, function() { 
   MyGame.calculateDimensions();            
   this.scale.setGameSize(MyGame.canvasWidth, MyGame.canvasHeight);        
}, this);

jQuery method
$(window).resize(function() { resizeGame(); } );
    function resizeGame() {
    var innerWidth = window.innerWidth;
    var innerHeight = window.innerHeight;
    var gameRatio = innerWidth/innerHeight;
    game.width = Math.ceil(320*gameRatio);
    game.height = 320;
    game.stage.bounds.width = Math.ceil(320*gameRatio);
    game.stage.bounds.height = 320;
    game.scale.refresh();
}