Search code examples
javascripthtmlobjectcanvasmove

Javascript: Moving object on canvas (trying to learn object oriented programming)


So basicly I want to make a simple Snake game, but I'm stuck already at the moving part.

This is the code that works if I make a button onclick = "snake.show()" and as I click the button, the rectangle moves. (snake.show() is also in the body onload)

    var width = 800;
    var height = 400;
    var x = width/2;
    var y = height/2;

    class Snake{
        show(){
            var c = document.getElementById("canvas");
            var ctx = c.getContext("2d");
            ctx.rect(x, y, 20, 5);
            ctx.fill();
            x++;
        }
        //update(){}
    }

    let snake = new Snake();

but instead of that i want to make something like this:

    var width = 800;
    var height = 400;
    var x = width/2;
    var y = height/2;

    class Snake{
        show(){
            var c = document.getElementById("canvas");
            var ctx = c.getContext("2d");
            ctx.rect(x, y, 20, 5);
            ctx.fill();
        }
        update(){
            x++;
        }
    }

And call the update() function if I need to move the rectangle, but this does not work. Sorry for my bad english, thanks for the advices and for the help!


Solution

    1. Declare the canvas and the context as global variables (only once).
    2. A class need a constructor method.
    3. I'm updating and showing again the snake on keydown the right arrow.

    I hope it helps.

    const c = document.querySelector("canvas");
    const ctx = c.getContext("2d");
    
    const width = (c.width = 800);
    const height = (c.height = 400);
    
    class Snake {
      constructor() {
        this.x = width / 2;
        this.y = height / 2;
      }
      show() {
        ctx.beginPath();
        ctx.rect(this.x, this.y, 20, 5);
        ctx.fill();
      }
      update() {
        this.x+=20;
      }
    }
    
    let snake = new Snake();
    snake.show();
    
    window.addEventListener("keydown", e => {
      
      if (e.keyCode == 39) {
        ctx.clearRect(0,0,width,height);
        snake.update();
        snake.show();
      }
    });
    canvas{border:1px solid}
    <canvas id="canvas"></canvas>