setInterval方法不起作用

时间:2017-08-07 04:27:37

标签: javascript html5 setinterval

我一直在尝试制作HTML游戏。所以我尝试使用setInterval方法每50毫秒绘制一次画布。但这不起作用。我尝试了一切,但它不起作用。以下是我的代码。

<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>

0 个答案:

没有答案