部分代码
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <style> * { margin: 0; padding: 0; } html, body { width: 100%; height: 100%; overflow: hidden; } </style> <title>Web FlappyBird</title> </head> <body> <canvas id="game_canvas" width="375" height="667"></canvas> <script type="module" src="game.js"></script> </body> </html>
main.js
//初始化整个游戏的精灵,作为游戏开始的入口 import {ResourceLoader} from "./base/ResourceLoader.js"; import {Director} from "./Director.js"; import {BackGround} from "./runtime/BackGround.js"; import {DataStore} from "./base/DataStore.js"; export class Main { constructor() { this.canvas = document.getElementById('game_canvas'); this.ctx = this.canvas.getContext('2d'); this.dataStore = DataStore.getInstance(); const loader = ResourceLoader.create(); loader.onLoaded(map => this.onResourceFirstLoaded(map)) let image = new Image(); image.src = '../res/background.png'; image.onload = () => { this.ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, image.width, image.height, ) } console.log(window.innerWidth,window.innerHeight); } onResourceFirstLoaded(map) { this.dataStore.ctx = this.ctx; this.dataStore.res = map; this.init(); } init() { this.dataStore.put('background', BackGround); Director.getInstance().run(); } }
background.js
//背景类 import {Sprite} from "../base/Sprite.js"; export class BackGround extends Sprite { constructor() { const image = Sprite.getImage('background'); super(image, 0, 0, image.width, image.height, 0, 0, window.innerWidth, window.innerHeight); this.x = 0; this.xspeed = 2; } draw() { this.x = this.x + this.xspeed; console.log(window.innerWidth,window.innerHeight); if (this.x > 100) { this.x = 0; } super.draw(this.img, this.srcX, this.srcY, this.srcW, this.srcH, -this.x, this.y, this.width, this.height); } }
Director.js
//导演类,控制游戏的逻辑 import {DataStore} from "./base/DataStore.js"; export class Director { constructor() { this.datastore = DataStore.getInstance(); } static getInstance() { if (!this.instance) { this.instance = new Director(); } return this.instance; } run() { this.datastore.get('background').draw(); requestAnimationFrame(() => this.run()); } }
小白求解,图片放不满屏幕
流觞醉月