【问题标题】:Javascript: Moving object on canvas (trying to learn object oriented programming)Javascript:在画布上移动对象(尝试学习面向对象编程)
【发布时间】:2019-02-25 13:05:40
【问题描述】:

所以基本上我想做一个简单的贪吃蛇游戏,但我已经卡在移动部分了。

如果我创建一个按钮 onclick = "snake.show()" 并且当我单击该按钮时,矩形移动,这就是有效的代码。 (snake.show() 也在body onload中)

    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() 函数,但这不起作用。抱歉我的英语不好,感谢您的建议和帮助!

【问题讨论】:

    标签: javascript html object canvas move


    【解决方案1】:
    1. 将画布和上下文声明为全局变量(仅一次)。
    2. 一个类需要一个构造方法。
    3. 我正在更新并再次在 keydown 右箭头上显示蛇。

    希望对你有帮助。

    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>

    【讨论】:

    • 一个类确实需要一个构造函数,但你不必自己指定它。如果省略,将使用默认构造函数。
    猜你喜欢
    • 2015-04-16
    • 1970-01-01
    • 2011-01-30
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-23
    相关资源
    最近更新 更多