JavaScript:在画布上移动对象(尝试学习面向对象的编程)



基本上我想制作一个简单的蛇游戏,但是我已经卡在移动的部分上。

这是如果我在按钮上进行按钮=" snake.show()",并且在单击按钮时,矩形移动。(Snake.show()也在体内)

    var width = 800;
    var height = 400;
    var x = width/2;
    var y = height/2;
    class Snake{
        show(){
            var c = document.getElementById("canvas");
            var ctx = c.getContext("2d");
            ctx.rect(x, y, 20, 5);
            ctx.fill();
            x++;
        }
        //update(){}
    }
    let snake = new Snake();

,但我想做些这样的事情:

    var width = 800;
    var height = 400;
    var x = width/2;
    var y = height/2;
    class Snake{
        show(){
            var c = document.getElementById("canvas");
            var ctx = c.getContext("2d");
            ctx.rect(x, y, 20, 5);
            ctx.fill();
        }
        update(){
            x++;
        }
    }

,如果我需要移动矩形,请调用update()函数,但这不起作用。对不起,我的英语不好,感谢您的建议和帮助!

  1. 将画布和上下文声明为全局变量(仅一次)。
  2. 类需要构造方法。
  3. 我正在更新,并再次显示钥匙down上正确箭头的蛇。

我希望它有帮助。

const c = document.querySelector("canvas");
const ctx = c.getContext("2d");
const width = (c.width = 800);
const height = (c.height = 400);
class Snake {
  constructor() {
    this.x = width / 2;
    this.y = height / 2;
  }
  show() {
    ctx.beginPath();
    ctx.rect(this.x, this.y, 20, 5);
    ctx.fill();
  }
  update() {
    this.x+=20;
  }
}
let snake = new Snake();
snake.show();
window.addEventListener("keydown", e => {
  
  if (e.keyCode == 39) {
    ctx.clearRect(0,0,width,height);
    snake.update();
    snake.show();
  }
});
canvas{border:1px solid}
<canvas id="canvas"></canvas>

最新更新