0

i didn't understand why my canvas wasn't drawn. With a little of debugging i discovered that at row 35 the property x of the object "item" returns undefined [ canvasContext.fillRect(item.x, item.y, 5, 5) ]. Someone can explain me why?

var players = [];
players.push(new Player(100, 200));
players.push(new Player(300, 200));
players.push(new Player(400, 400));
players.push(new Player(200, 200));

function Player(x, y) {
  this.x = x;
  this.y = y;
}

function auto() {
  setInterval(
    function() {
      movePlayers();
      updateCanvas();
    },
    1000
  );
}

function movePlayers() {
  for (var item in players) {
    item.x += 1;
    item.y += 1;
  }
}

function updateCanvas() {
  var canvas = document.getElementById("canvas");
  var canvasContext = canvas.getContext("2d");
  canvasContext.clearRect(0, 0, canvas.width, canvas.height);
  for (var item in players) {
    canvasContext.fillRect(item.x, item.y, 5, 5);
  }

}
auto()
<canvas id="canvas"></canvas>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
lampaDT
  • 13
  • 1
  • I tried to make you a snippet. It does not seem to do anything. You need to draw a rectangle, no? – mplungjan Jun 17 '19 at 11:14
  • 1
    Anyway, don't use for..in for arrays `for (var item in players) {` – mplungjan Jun 17 '19 at 11:15
  • `for (var item in players)` you are iterating over the *indeces*, not the objects in the array. So, `index` will be `0`, `1`, etc which don't have an `x` and `y` property. – VLAZ Jun 17 '19 at 11:23

1 Answers1

1

Please do not use for..in for arrays.

players.forEach(item => canvasContext.fillRect(item.x, item.y, 5, 5) )

works better

Also next time make a runnable example (my canvas was too small)

function Player(x, y) {
  this.x = x;
  this.y = y;
}

function auto() {
  setInterval(
    function() {
      movePlayers();
      updateCanvas();
    },
    1000
  );
}

function movePlayers() {
  for (var item of players) {
    item.x += 1;
    item.y += 1;
  }
}

function updateCanvas() {
  canvasContext.clearRect(0, 0, canvas.width, canvas.height);
  players.forEach(item => canvasContext.fillRect(item.x, item.y, 5, 5) )
}
var canvas = document.getElementById("canvas");
var canvasContext = canvas.getContext("2d");
var players = [new Player(10, 20),
new Player(30, 20),
new Player(40, 40),
new Player(20, 20)
];
auto()
canvas { border:1px solid #d3d3d3; }
<canvas id="canvas"></canvas>
mplungjan
  • 169,008
  • 28
  • 173
  • 236