Get started with phaser CDN

MIT licensed

Phaser: HTML5 library, JS, interactive games, applications.

Tags:
  • HTML5
  • game
  • canvas
  • 2d
  • WebGL
  • web audio
  • physics
  • tweens
  • javascript
  • typescript

Stable version

Copied!

How to start using phaser CDN


// Create a new Phaser game with a 800px width and 600px height
const game = new Phaser.Game({
  type: Phaser.CANVAS,
  parent: 'game-container', // replace with the id of your HTML element
  width: 800,
  height: 600,
  physics: {
    default: 'arcade',
    arcade: {
      gravity: { y: 200 }
    }
  },
  scene: {
    preload: PreloadScene,
    create: CreateScene,
    update: UpdateScene
  }
});

// Preload assets
class PreloadScene extends Phaser.Scene {
  preload() {
    this.load.image('ground', 'assets/ground.png');
    this.load.image('player', 'assets/player.png');
  }
}

// Create game objects
class CreateScene extends Phaser.Scene {
  create() {
    this.ground = this.physics.add.staticGroup();
    this.ground.create(400, 570, 'ground').setScale(2).refreshBody();

    this.player = this.physics.add.sprite(100, 550, 'player');
    this.player.setBounce(0.2);
    this.player.setCollideWorldBounds(true);

    this.cursors = this.input.keyboard.createCursorKeys();

    this.physics.add.collider(this.ground, this.player);

    this.anims.create({
      key: 'run',
      frames: this.anims.generateFrameNumbers('player', { start: 0, end: 3 }),
      frameRate: 10,
      repeat: -1
    });
  }
}

// Update game logic
class UpdateScene extends Phaser.Scene {
  update(time, delta) {
    if (this.cursors.left.isDown) {
      this.player.setAccelerationX(-500);
    } else {
      this.player.setAccelerationX(0);
    }

    if (this.cursors.right.isDown) {
      this.player.setAccelerationX(500);
    }
  }
}
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!

All versions