I wrote a small program in javascript where a person is basically moving over a field hunting mushrooms, after every move (N,E,S,W) i want to redraw the whole canvas and i also want to see it on my browser in the HTML canvas object. I tried to use requestAnimationFrame but i only see the canvas at the end of the program, while the program is running the browser is jut white, but i want to refresh the picture everytime the person moves, i tried it like this:
function Guy(startPosition) {
this.position = startPosition;
}
Guy.prototype.moveTo = function (direction) {
if (direction == "N") this.position.x -= 1
else if (direction == "S") this.position.x += 1
else if (direction == "W") this.position.y -= 1
else if (direction == "E") this.position.y += 1
checkIfMushroom(this.position);
requestAnimationFrame(drawField);
}
And then i have this function, in which the player moves to the mushroom (changing its x and y coordinates):
function walktToMushroom(pos) {
while (!player.position.equals(pos)) {
var dx = player.position.x - pos.x;
var dy = player.position.y - pos.y;
while (dx != 0) {
if (dx < 0) player.moveTo("S");
else player.moveTo("N");
dx = player.position.x - pos.x;
}
while (dy != 0) {
if (dy < 0) player.moveTo("E");
else player.moveTo("W");
dy = player.position.y - pos.y;
}
}
}
drawField just redraws everything (mushrooms, player, field) with ctx.stroke().
How can i update the frame everytime the player (which is of type Guy) moves?
Edit: drawField function:
function drawField() {
requestAnimationFrame(drawField);
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawRaster();
ctx.beginPath();
ctx.strokeStyle = "#2FA0FF";
ctx.lineWidth = 3;
ctx.rect(player.position.x * rasterSize, player.position.y * rasterSize, rasterSize, rasterSize);
ctx.stroke();
ctx.closePath();
mushrooms.forEach(function (mush) {
ctx.beginPath();
ctx.strokeStyle = "#A120FF";
ctx.lineWidth = 3;
ctx.rect(mush.x * rasterSize, mush.y * rasterSize, rasterSize, rasterSize);
ctx.stroke();
ctx.closePath();
});
}
drawField();
requestAnimationFramefunction and just directly calldrawField()?drawField()i can see the single steps!walktToMushroom(pos)you might be clearing the canvas faster than it can draw thus just showing white. (also typo with your function name, the extra "t"? "walktTo..")