clearRect不清除画布

时间:2017-11-06 20:09:55

标签: javascript canvas html5-canvas

我正在开发一个游戏作为编码练习,我遇到了一个我无法找到的错误,当我按下所选按钮时它不会删除形状并重新绘制一个它由于某种原因只是保持页面上的形状和绘制一个新的shae我需要它来删除旧的形状并重新绘制一个新的形状this is how the game should work    在这里输入代码



window.addEventListener("load", function() {
 
  function clear(ctx, width, height) {

  }

  function drawRandomShape(width, height) {
    //ctx.clearRect(0,0, canvas.width, canvas.height)
    canvas.style.backgroundColor = 'white';
   // var num = Math.floor(Math.random() * 10)

    var number = 30;
    var countdown = setInterval(function(){
      timerSpan.innerHTML = number--;
      //console.log(number)
      if(number == 0 - 1){
        clearInterval(countdown);
      }
    },1000);
    function randomShape(){
      var randomNum = Math.floor(Math.random() * 10);
      //ctx.clearRect(0,0, canvas.width, canvas.height)
     // if(number > 0){
        if(randomNum >= 0 && randomNum <= 2){
      //    ctx.clearRect(0, 0, canvas.width, canvas.height);
          var triangle = ctx.beginPath();
          triangle += ctx.moveTo(0, 0);
          triangle += ctx.lineTo(90, 90);
          triangle += ctx.lineTo(0, 90);
          triangle += ctx.closePath();
          triangle += ctx.fillStyle = "red";
          triangle += ctx.fill();

          document.addEventListener('keyup', function shape(e){
            if(e.keyCode == 37){        
              triangle += ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
              document.removeEventListener('keyup', shape);
              randomShape();
            }
          });
        }else if(randomNum > 2 && randomNum <= 4){
        //  ctx.clearRect(0,0, canvas.width, canvas.height);   
          var blackTriangle = ctx.fillStyle = "black";
          blackTriangle += ctx.beginPath();
          blackTriangle += ctx.moveTo(0,0);
          blackTriangle += ctx.lineTo(90, 90);
          blackTriangle += ctx.lineTo(0, 90);
          blackTriangle += ctx.fill();

          document.addEventListener('keyup', function shape(e){
            if(e.keyCode == 38){
              blackTriangle += ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
              document.removeEventListener('keyup', shape);
              randomShape();
            }
          });
        }else if(randomNum >= 4 && randomNum <= 6){
          //ctx.clearRect(0, 0, canvas.width, canvas.height);
          var redSquare = ctx.fillStyle = 'black';
          redSquare += ctx.rect(200, 100, 90, 90)
          redSquare += ctx.fill();
          document.addEventListener('keyup', function shape(e){
            if(e.keyCode == 39){
              redSquare += ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
              randomShape()
            }
          });
          
        }else if(randomNum > 6 && randomNum < 10){
          //ctx.clearRect(0,0, canvas.width, canvas.height);
          var whiteSquare = ctx.rect(50,70,90,90);
          whiteSquare += ctx.fillStyle = 'red';
          whiteSquare += ctx.fill();

          document.addEventListener('keyup', function shape(e) {
            if(e.keyCode == 40){
              whiteSquare += ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
              document.removeEventListener('keyup', shape);
              randomShape();
            }
          });
        }
        console.log(randomNum)
      //};
    }
    randomShape();
  }
  //}, 1000);
  function drawGameStartText(width, height ,score) {
    width = 170;
    height = 350;
    ctx.fillStyle = 'White';
    ctx.font = '30px Verdana'
    ctx.fillText('Press space bar to start a new game' , width , height);
  }

  function restartGame(ctx, width, height){

  }

      var canvas = document.getElementById("shapes-game"),
      height = canvas.scrollHeight,
      width = canvas.scrollWidth,
      gameOn = false,
      expectedKey = undefined,
      ctx = canvas.getContext('2d'),
      // white triangle = up, red square = down,
      // red triangle = left, white square = right
      expectedKeysMap = {white0: 38, red1: 40, red0: 37, white1: 39};
      timerSpan = document.getElementById("time-remaining");

      scoreSpan = document.getElementById("score-val"),
      seconds = 3;
     // intervalId;
  document.addEventListener("keyup", function(e) {
    e.preventDefault();
    if(e.keyCode == 32){
      drawRandomShape();
    }
  });
  drawGameStartText()
})
&#13;
body {
  padding-bottom: 50px;
}

#shapes-game {
  border: 4px solid grey;
  background-color: black;
}

.canvas-container {
  padding: 10px;
}
.canvas-container, #shapes-game {
  height: 750px;
  width: 800px;
}

.scores {
  padding: 10px;
  text-align: center;
}

.legend {
  padding-top: 15px;
}

.legend-contents {
  text-align: left;
  padding-left: 30px;
}

.triangle-bottomleft-red {
  width: 0;
  height: 0;
  border-bottom: 50px solid red;
  border-right: 50px solid transparent;
}

.triangle-bottomleft-black {
  width: 0;
  height: 0;
  border-bottom: 54px solid black;
  border-right: 58px solid transparent;
}

.triangle-inner-white {
    position: relative;
    top: 2px;
    left: 2px;
    width: 0;
    height: 0;
    border-bottom: 50px solid white;
    border-right: 50px solid transparent;
}

.triangle-left {
    width: 0;
    height: 0;
    border-top: 23px solid transparent;
    border-bottom: 23px solid transparent;
    border-right: 23px solid red;
}

.inner-triangle {
    position: relative;
    top: -20px;
    left: 2px;
    width: 0;
    height: 0;
    border-top: 20px solid transparent;
    border-bottom: 20px solid transparent;
    border-right: 20px solid blue;
}

.red-square {
  width: 50px;
  height: 50px;
  background-color: red;
}

.white-square {
  width: 50px;
  height: 50px;
  background-color: white;
  border-style: solid;
  border-width: 1px;
}
&#13;
<!DOCTYPE html>
<html>
<head>
  <title>Shapes!!</title>
  <link rel="stylesheet" type="text/css" href="vendor/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="styles.css">
  <script type="text/javascript" src="vendor/jquery-1.12.4.min.js"></script>
  <script type="text/javascript" src="vendor/bootstrap.min.js"></script>
  <script type="text/javascript" src="index.js"></script>
</head>
<body>
  <div class="container">
    <div class="col-xs-10 canvas-container">
      <canvas id="shapes-game" height="750" width="800"></canvas>
    </div>
    <div class="col-xs-2 scores">
      <h1>Score</h1>
      <h3><span id="score-val">0</span></h3>
      <h1>Timer</h1>
      <h3><span id="time-remaining">30</span></h3>
      <div class="legend">
        <h1>Legend</h1>
        <div class="legend-contents">
          <div class="triangle-bottomleft-red">
          </div>
          <h4>Left</h4>
          <div class="white-square">
          </div>
          <h4>Right</h4>
          <div class="triangle-bottomleft-black">
            <div class="triangle-inner-white"></div>
          </div>
          <h4>Up</h4>
          <div class="red-square">
          </div>
          <h4>Down</h4>
        </div>
      </div>
    </div>
  </div>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您的代码存在许多问题。

你为什么要做的第一个

   var blackTriangle = ctx.fillStyle = "black";
   blackTriangle += ctx.beginPath();

因为它绝对没有。

创建一个密钥处理程序并处理其中的所有内容而不是

  document.addEventListener('keyup', function shape(e){
    if(e.keyCode == 39){
      redSquare += ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
      randomShape()
    }
  });

您只是在创建一堆关键处理程序。

如果要跟踪要绘制的形状,请为每个形状创建一个数组

  const shapes = {
    whiteSquares : [],
    redSquares : [],
    whiteTriangle : [],
    redTriangle: [],  
  };

然后在添加形状时将其添加到相应的数组

    if(randomNum <= 2){
      ctx.beginPath();
      ctx.lineTo(0, 0);
      ctx.lineTo(90, 90);
      ctx.lineTo(0, 90);
      ctx.closePath();
      ctx.fillStyle = "red";
      ctx.fill();
      shapes.redTriangle.push([0,0]); // store the top left of the triangle
    }

然后你可以在密钥处理程序中清除它

  var gameStarted = false;
  const keyNames = {
    space : 32,
    left : 37;
    up : 38,
    right : 39,
    down : 40,
  }
  // only one key handler needed.
  document.addEventListener('keyup', e => {
    if(gameStarted === false && e.keyCode === keyNames.space) { 
      gameStarted = true;
      drawRandomShape();
    }else if(e.keyCode === keyNames.left) { 
      if(shapes.redTriangle.length > 0){
        var pos = shapes.redTriangle.shift(); // remove the bottom item in the array
        ctx.clearRect(pos[0],pos[1],90,90); // clear that position
        randomShape();  // create anothe shape.          
      }    
    }else if(e.keyCode === keyNames.right) { 
      if(shapes.whiteSquares.length > 0){
        // same as above
      }    
    }else if(e.keyCode === keyNames.up) { 
      if(shapes.whiteTriangle.length > 0){
        // same as above
      }
    }else if(e.keyCode === keyNames.down) { 
      if(shapes.redSquares.length > 0){
        // same as above
      }
    }
  }

不要使条件语句复杂化。

你有

    var randomNum = Math.floor(Math.random() * 10);

    if(randomNum >= 0 && randomNum <= 2){
        // do stuff
    }else if(randomNum > 2 && randomNum <= 4){
        // do stuff
    }else if(randomNum >= 4 && randomNum <= 6){
        // do stuff
    }else if(randomNum > 6 && randomNum < 10){
        // do stuff
    }

相同
    var randomNum = Math.floor(Math.random() * 10);

    if (randomNum <= 2) { 
        // do stuff
    } else if(randomNum <= 4) { 
        // do stuff
    } else if(randomNum <= 6) { 
        // do stuff
    } else { 
        // do stuff
    }