Skip to content Skip to sidebar Skip to footer

2048 In Javascript: Updating The Canvas

I am in a computer science class at my high school, and for my final project, my partner and I have decided to make 2048. We are not going to have the tiles 'move', but instead, th

Solution 1:

What your game needs is a game loop. So the drawing needs to happen continously, at the moment you draw only one time at the beginning.

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

functiondraw() {
    // clear the canvas so the old rectangles are gone
    ctx.clearRect(0, 0, c.width, c.height);

    // grey rectangle
    ctx.beginPath();
    ctx.lineWidth = "2";
    ctx.strokeStyle = "grey";
    ctx.rect(5, 5, 400, 400);
    ctx.stroke();

    // blue rectangle
    ctx.beginPath();
    ctx.lineWidth = "5";
    ctx.strokeStyle = "blue";
    ctx.rect(x, y, 100, 100);
    ctx.stroke();
    ctx.fillStyle = "blue";
    ctx.fill();
}

// repeat game loop function forever, 30 times per secondwindow.setInterval(draw, 1000.0 / 30.0)

Notice the use of window.setInterval and ctx.clearRect.

Solution 2:

Every time you want to update what is shown on the canvas, you have to 'Draw' again. Your code will run once when the page loads but never draws again so your changes to x and y are never seen.

I added a draw function here that is called on startup and after each keydown.

<!DOCTYPE html><htmllang = "en"><bodystyle="background-color:lightgrey;"><title>2048</title><canvasid="myCanvas"width="410"height="410"style="border:1px solid #d3d3d3;"></canvas><script>var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var x = 10;
var y = 10;   

document.addEventListener('keydown', function(event)
{
    if(event.keyCode == 37)//left
    {
        x -= 100;
        console.log("x:"+ x);
    }
    elseif(event.keyCode == 38)//up
    {
        y -= 100;
        console.log("y:"+ y);
    }
    elseif(event.keyCode == 39)//right
    {
        x += 100;
        console.log("x:"+ x);
    }
    elseif(event.keyCode == 40)//down
    {
        y += 100;
        console.log("y:"+ y);
    }
    draw();
});

functiondraw(){   
  ctx.clearRect(0, 0, c.width, c.height); 
  // grey rectangle
  ctx.beginPath();
  ctx.lineWidth = "2";
  ctx.strokeStyle = "grey"; 
  ctx.rect(5, 5, 400, 400);
  ctx.stroke();

  // blue rectangle
  ctx.beginPath();
  ctx.lineWidth = "5";
  ctx.strokeStyle = "blue";
  ctx.rect(x, y, 100, 100);
  ctx.stroke();
  ctx.fillStyle = "blue";
  ctx.fill();  
}

draw();

</script></body></html>

Post a Comment for "2048 In Javascript: Updating The Canvas"