Search code examples
javascriptvariablescanvasrectangles

Not setting variable to rectangle in canvas


I am trying to get the rectangle to move when you click a button by adding 1 to the x/y pos of the rectangle but the speed variable keeps saying undefined.

      // . . . //

      function component(width, height, color, x, y) {
      this.width = width;
      this.height = height;
      this.speedX = 0;
      this.speedY = 0;
      this.x = x;
      this.y = y;
      this.update = function(){
        ctx = gameArea.context;
        ctx.fillStyle = color;
        ctx.fillRect(this.x, this.y, this.width, this.height); 
      }
      this.newPos = function(){
        this.x += this.speedX;
        this.y += this.speedY;
      }
  }


    function updateGameArea(){// Update games at 50fps
       gameArea.clear();
       bluePiece.newPos();
       bluePiece.update();
  }


  function moveUp(piece){
    piece.speedY -= 1;
    console.log("UP "+piece+" S:"+piece.speedY);
  }
  function moveDown(piece){
    piece.speedY += 1;
    console.log("DOWN "+piece+" S:"+piece.speedY);
  }
  function moveLeft(piece){
    piece.speedX -= 1;
    console.log("LEFT "+piece+" S:"+piece.speedX);
  }
  function moveRight(piece){
    piece.speedY += 1;
    console.log("RIGHT "+piece+" S:"+piece.speedX);
  }

Note: If you would like to see the full code to better understand what is going on, please go here and press ctrl+U to view full code.


Solution

  • you are passing a string to the function and after that accessing the property of String, which definitely will be undefined.
    Try console.log(typeof piece);