user4348719
user4348719

Reputation: 351

Game loop not doing what its supposed to

Hi I'm trying to make a very simple game using javascripts canvas element. I have a rectangle thats drawn on the canvas and I would like for it to move across the canvas when user clicks a button but its not working.
here is my html:

<style>
canvas {
border: 1px solid black;
height: 300px;
width:500px;
}
</style>
</head>
<body>

<button id = "play">Click to play</button>
</body>

My javascript:

$( document ).ready(function() {
var x = document.createElement("CANVAS");
var ctx = x.getContext("2d");
ctx.fillStyle = "#FF0000";
var x1 = 10;
var y = 10;
ctx.fillRect(x1, y, 80, 10);
document.body.appendChild(x);

var Game = {stopped:true};;

Game.draw = function() { 
    ctx.fillRect(x1, y, 80, 10);
};
Game.update = function() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    x1 = x1+5;

};

Game.run = function() {
    Game.update();
    Game.draw();
};

$("#play").click(function() {

    Game.stopped = false;
    while (!Game.stopped){
        Game.run(); 
    }


});
});

Upvotes: 0

Views: 38

Answers (2)

Yangguang
Yangguang

Reputation: 1785

There is another simple implement:

    $(document).ready(function () {
    var canvas = document.createElement("CANVAS");
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "#FF0000";
    var x1 = 10;
    var y = 10;
    ctx.fillRect(x1, y, 80, 10);
    document.body.appendChild(canvas);

    var Game = {stopped: true};
    ;

    Game.draw = function () {
        ctx.fillRect(x1, y, 80, 10);
    };
    Game.update = function () {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        x1 = x1 + 5;

    };

    Game.run = function () {
        Game.update();
        Game.draw();
    };

    $("#play").click(function () {

        Game.stopped = false;
        // while (!Game.stopped) {
//                Game.run();                
            // }

        if(!Game.stopped){
            setInterval(Game.run,1000);
        }


    });
});

For animation, it's better to use Window.requestAnimationFrame(), if you want to get a better performance.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388436

There are multiple problems in your script.

  1. there is no variable called, canvas it is x
  2. Your loop is an infinite while loop, which does not give any time for the UI to update - since browser tab is a single threaded app both js execution and the repaint/refresh of the UI happens in the same thread

So

var interval;
$("#play").click(function () {
    Game.stopped = false;
    interval = setInterval(Game.run, 5);
});
$("#stop").click(function () {
    Game.stopped = true;
    clearInterval(interval);
});

Demo: Fiddle

Upvotes: 1

Related Questions