html代码
<canvas width="500" height="500"></canvas>
<script src="./6.2-walk.js"></script>
<script>
let canvas = new Walk("canvas");
</script>
js代码
class Walk {
constructor(canvas) {
this.initCanvasAndImg(canvas);
window.onload = () => { // window.onload 必须等到页面内容包括图片的所有元素和资源加载完毕后才能执行
this.drawBg(); // 调用草地背景图
this.drawImg(); // 调用 小矮人图像
this.move(canvas); // 调用小矮人移动方法
this.direction(); // 调用方向方法
}
}
// 初始化画布和图片
initCanvasAndImg(canvas) {
this.canvas = document.querySelector(canvas); // 获取 canvas 画布
// console.log(this.canvas);
this.cW = this.canvas.width; // 获取画布的宽
this.cH = this.canvas.width; // 获取画布的高
this.ctx