1.封装Game类
import Man from './Man.js';
import Map from './Map.js';
class Game {
//在new的时候执行初始化代码
constructor() {
this.initCanvas(); //初始化Canvas
this.KeyDown();
this.initMan();//初始化小矮人
this.map = new Map();//初始化map
}
//初始化小矮人
initMan() {
this.man = new Man();
}
//初始化Canvas
initCanvas() {
this.canvas = document.getElementById('mycanvas');
this.context = this.canvas.getContext('2d');
//获取实例化对象里的canvas的宽高
this.h = this.canvas.height;
this.w = this.canvas.width;
}
//键盘事件
KeyDown() {
//键盘按下事件
window.onkeydown = () => {
// console.log(event.keyCode);
//keyCode:上38 下40 左37 右39
switch (event.keyCode) {
case 38://上
this.man.derection = 3;
break;
case 40://下
this.man.derection = 0;
break;
case 37://左
this.man.derection = 1;
break;
case 39://右
this.man.derection = 2;
break;
}
}
}
//开始游戏事件
start() {
setInterval(() => {
//清除画布
this.context.clearRect(0, 0, this.w, this.h);
//绘制地图
this.map.draw(this.context, this.w, this.h);
//绘制小矮人
this.man.draw(this.context, this.w, this.h);
}, 300)
}
}
export default Game;
2.封装绘制小矮人图片类
//小矮人相关的东西
class Man {
constructor() {
this.initImage();//初始化图片
this.initData();//初始化数据
}
//创建图片
initImage() {
this.img = document.createElement('img');
this.img.src = './img/DMMban.png';
}
//创建数据
initData() {
this.manW = 40;//小矮人的宽度
this.manH = 65;//小矮人的高度
this.x = 0;//在canvas上面绘制的x坐标
this.y = 0;//在canvas上面绘制的y坐标
this.cutX = 0;//裁剪的图片x坐标
this.derection = 2;//方向 默认向右走 1:向左走
}
//绘制小矮人
draw(context, w, h) {
//执行绘制图片
context.drawImage(this.img, this.cutX, this.manH * this.derection, this.manW, this.manH, this.x, this.y, this.manW, this.manH);
switch (this.derection) {
case 2://向右
this.x += 6;
break;
case 1://向左
this.x -= 6;
break;
case 0://向下
this.y += 6;
break;
case 3://向上
this.y -= 6;
break;
}
this.cutX += this.manW;
if (this.cutX > 120) {
this.cutX = 0;
}
}
}
export default Man;
3.封装背景类
// 地图 背景
class Map {
constructor() {
this.initImage();
}
initImage() {
this.img = new Image();
this.img.src = './img/green.webp';
}
draw(context, W, H) {
context.drawImage(this.img, 0, 0, W, H);
}
}
export default Map;
4.调用Game类开始游戏
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
canvas {
border: 2px solid #f00;
}
</style>
</head>
<body>
<button id="startGameBtn">开始游戏</button>
<br>
<canvas id="mycanvas" width="500" height="500"></canvas>
<script type="module">
import Game from './Game.js'; //引入Game.js模块
let startGameBtn = document.querySelector('#startGameBtn');//获取button标签
let game = new Game();//创建Game的实例对象
//给button按钮添加点击事件
startGameBtn.onclick = function () {
game.start();//调用Game里面的start开始方法
}
</script>
</body>
</html>
运行效果:可以通过键盘上下左右键控制行走的方向