-2

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();
}
Bip901
  • 590
  • 6
  • 22
  • 1
    You nees to pass 'render' as a function reference instead of calling it when you create your interval. – zero298 Jul 30 '19 at 11:09

2 Answers2

1

Because your function move() is never used.It can updating if you change its height or width:)

user7854319
  • 65
  • 1
  • 1
  • 6
  • It *is* used, I just didn't include the code here because I thought it isn't necessary. I used buttons to change it, and checked that the var itself is actually changing. – Bip901 Apr 12 '17 at 15:53
1

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>
tuhin47
  • 5,172
  • 4
  • 19
  • 29