Search code examples
javascripthtmlcanvas2d-games

HTML Canvas doesn't update


When I call move() the "y" variable is changed but the box is still rendered in the same position.

var c = document.getElementById("can");  //my canvas id is "can"  
var pen = c.getContext("2d");
var y = 200;
setInterval(render(y), 1000/30); //update 30 times per second

function move(dir){
    y=y+dir;
}

function render(height) {
    pen.beginPath();
    pen.clearRect(0,0,888,500);
    pen.beginPath();
    pen.rect(30,height,50,50); //Draw the player
    pen.fillStyle="green";
    pen.fill();
}

Solution

  • You have to call move and render inside setInterval.

    var c = document.getElementById("can"); //my canvas id is "can"  
    var pen = c.getContext("2d");
    var y = 0;
    var dir = 20;
    
    function dirValue(val) {
      dir = val;
    }
    setInterval(function() {
      move(dir);
      render(y);
    }, 1000); //update 30 times per second
    function move(dir) {
      return y = y + dir;
    }
    
    function render(height) {
      //console.log(height);
      pen.beginPath();
      pen.clearRect(0, 0, 888, 500);
      pen.beginPath();
      pen.rect(30, height, 50, 50); //Draw the player
      pen.fillStyle = "green";
      pen.fill();
    }
    <button type='button' onclick='dirValue(20)'>Down</button>
    <button type='button' onclick='dirValue(-20)'>UP</button>
    <button type='button' onclick='dirValue(0)'>Stop</button>
    <canvas id="can" width="1000" height="1000"></canvas>