0

I have been trying to make a html game. So I trying to use setInterval method for drawing canvas at at every 50 ms. But this is not working. I tried everything but it's not working. Below is my code.

<body>
<canvas id="canvas" width="330" height="330"></canvas>
<script>
var Game = {
    canvas: document.getElementById("canvas"),
    width: this.canvas.width,
    height: this.canvas.height,
    ctx: this.canvas.getContext("2d"),

    init: function(){
        this.drawCanvas();
        this.drawAtInterval();
        this.drawSnake(0, 0, 10, 10);
    },
    drawCanvas: function(){
        this.ctx.fillStyle = "black";
        this.ctx.fillRect(0, 0, this.width, this.height);
    },
    clearCanvas: function(){
        this.ctx.clearRect(0, 0, this.width, this.height);
    },
    drawSnake: function(x, y, width, height){
        this.ctx.fillStyle = "green";
        this.ctx.fillRect(x, y, width, height);
        this.ctx.strokeStyle = "white";
        this.ctx.strokeRect(x, y, width, height);
        },
/* code below as drawAtInterval() is not working. */
    drawAtInterval: function(){
        var interval = setInterval(this.update_game, 50);
    },
    update: function(){
        var x = 0;
        var y = 0;
        var dx = 10;
        var dy = 0;
        x += dx;
        y += dy;
        this.drawSnake(x, y, 10, 10);
    },
    update_game: function(){
        this.clearCanvas();
        this.drawCanvas();
        this.update();
    }
};
Game.init();
</script>
</body>
Vikash Pal
  • 35
  • 5
  • 1
    With `setInterval(this.update_game, 50)` the `update_game` is called every `50` ms, but it is not called in the context of `this`. So in `update_game`, `this` refers - in the browser - to `window` and not to your object anymore. You have to [`bind`](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) the `this` to the function. – t.niese Aug 07 '17 at 04:33
  • If I'm correct would an arrow function also work here? – user7951676 Aug 07 '17 at 04:47
  • What is an arrow function? I never heard about it. – Vikash Pal Aug 07 '17 at 04:50
  • @user7951676 yes `setInterval(() => this.update_game(), 50);` would also work, but if you want to use that in the browser, you would - at the moment - need to use a transpiler like babel, because there are still to many people using browsers that do not support it. – t.niese Aug 07 '17 at 04:50
  • Ok, good to know, thank you – user7951676 Aug 07 '17 at 21:40

0 Answers0