【问题标题】:Not setting variable to rectangle in canvas未在画布中将变量设置为矩形
【发布时间】:2018-02-20 05:18:43
【问题描述】:

我试图通过在矩形的 x/y 位置上添加 1 来让矩形在单击按钮时移动,但速度变量一直显示未定义。

      // . . . //

      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);
  }

注意:如果您想查看完整代码以更好地了解发生了什么,请转到here 并按 ctrl+U 查看完整代码

【问题讨论】:

    标签: javascript variables canvas rectangles


    【解决方案1】:

    您将一个字符串传递给函数,然后访问字符串的属性,该属性肯定是未定义的。
    试试console.log(typeof piece);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多