如何更新写在画布上的文本

时间:2015-12-18 23:01:22

标签: javascript html canvas

当我尝试使用computerCount变量更改记分板时(正如您在ball变量的更新函数中的if语句中所见),其他数字未正确显示。请记住,在0开始正常工作。

Customize Json result in Web API

Screenshot of the Pong game - 您可以通过右上角的"编辑"来更改代码。在JSFiddle。

代码:

<!doctype html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Pong</title>

    <!-- Basic styling, centering the canvas -->
    <style>
    canvas{
      position: absolute;
      margin: auto;
      top:60px;
      bottom:0;
      right:0;
      left:0;
    }

    #scoreBoard{
      position: absolute;
      margin: auto;
      top:0;
      bottom:640px;
      right:720px;
      left:20px;
    }

    </style>
</head>

<body>

  <canvas id = "scoreBoard" width="500" height = "100"></canvas>
    <script>
        var WIDTH = 700
        var    HEIGHT = 600
        var    pi = Math.PI
          var  canvas
          var  ctx
          var  keystate
          var upArrow = 38;
          var downArrow = 40;
          var computerCount = 0;
          var playerCount = 0;

          var  player = {
                x: null,
                y: null,
                width: 20,
                height: 100,
                /**
                 * Update the position depending on pressed keys
                 */
                update: function() {
                if(keystate[upArrow]){
                   this.y-=7;
                 }
                 if(keystate[downArrow]){
                   this.y+=7;
                 }},
                /**
                 * Draw the player paddle to the canvas
                 */

                draw: function() {
                    ctx.fillRect(this.x, this.y, this.width, this.height);
                }
            }
            /**
             * The ai paddle
             *
             * @type {Object}
             */
          var  ai = {
                x: null,
                y: null,
                width: 20,
                height: 100,
                /**
                 * Update the position depending on the ball position
                 */
                update: function() {
                  var desty = ball.y-(this.height - ball.side)*0.5
                  this.y += (desty-this.y)*0.2;

                },

                draw: function() {
                    ctx.fillRect(this.x, this.y, this.width, this.height);
                }
            }
            /**
             * The ball object
             *
             * @type {Object}
             */
          var  ball = {
                x: null,
                y: null,
                vel:null,
                side: 20,
                speed:5,



                update: function() {

              this.x += this.vel.x;
              this.y += this.vel.y;

              if(0>this.y || this.y+this.side>HEIGHT){
                var offset = this.vel.y<0 ? 0-this.y : HEIGHT-(this.y+this.side);
                this.y+=2*offset
                this.vel.y*=-1;               
              }

              var AABBIntersect = function(ax, ay, aw, ah, bx, by, bw, bh) {
              return ax < bx+bw && ay < by+bh && bx < ax+aw && by < ay+ah;
                };


              var pdle = this.vel.x<0 ? player : ai;
              if(AABBIntersect(pdle.x,pdle.y,pdle.width,pdle.height, this.x, this.y, this.side, this.side)){

                this.x = pdle===player ? player.x + player.width : ai.x - this.side;

                var n = (this.y+this.side-pdle.y)/(pdle.height+this.side)
                var phi = 0.25*pi*(2*n - 1) // pi/4 = 45

                this.x = pdle===player ? player.x+player.width : ai.x - this.side;
                var n = (this.y+this.side - pdle.y)/(pdle.height+this.side);
                var phi = 0.25*pi*(2*n - 1); // pi/4 = 45
                this.vel.x = (pdle===player ? 1 : -1)*this.speed*Math.cos(phi);
                this.vel.y = this.speed*Math.sin(phi);

              }


                if(ball.x<0){
                  computerCount =+1;
                   ball.x = (WIDTH - ball.side) / 2;
            ball.y = (HEIGHT - ball.side) / 2;
                }

                },
                // reset the ball when ball outside of the canvas in the


                draw: function() {
                    ctx.fillRect(this.x, this.y, this.side, this.side);
                }
            }

            function score(){


            }
            /**
             * Starts the game
             */
        function main() {
            // create, initiate and append game canvas
            canvas = document.createElement("canvas");
            canvas.width = WIDTH;
            canvas.height = HEIGHT;
            ctx = canvas.getContext("2d");
            document.body.appendChild(canvas);

            canvas2 = document.createElement("canvas");
            canvas2.setAttribute("id", "scoreBoard");
            canvas2.width = 200;
            canvas2.height = 100;
            ctx2 = canvas2.getContext("2d");
            document.body.appendChild(canvas2);

            keystate = {};
            document.addEventListener("keydown" , function(event){
                keystate[event.keyCode] = true;
            })

            document.addEventListener("keyup" , function(event){
                delete keystate[event.keyCode];
            })

            init();

            var loop = function() {
                update();
                draw();
                window.requestAnimationFrame(loop, canvas);
            };
            window.requestAnimationFrame(loop, canvas);
        }
        /**
         * Initatite game objects and set start positions
         */
        function init() {
            player.x = player.width;
            player.y = (HEIGHT - player.height) / 2;
            ai.x = WIDTH - (player.width + ai.width);
            ai.y = (HEIGHT - ai.height) / 2;
            ball.x = (WIDTH - ball.side) / 2;
            ball.y = (HEIGHT - ball.side) / 2;
            ball.vel = {
              x:ball.speed,
              y: 0

            }


        }
        /**
         * Update all game objects
         */
        function update() {
            ball.update();
            player.update();
            ai.update();
        }

        function draw(){







          ctx.fillStyle = "black"
          ctx.fillRect(0,0,WIDTH,HEIGHT)

          ctx.save();
          ctx2.fillStyle = "red"
          ctx2.fillText(String(computerCount),100,100)
          ctx2.fillText("VS",120,100)
          ctx2.fillText(String(playerCount),175,100)
          ctx2.font = "bold 40px monaco"
          ctx.fillStyle = "white"
          ball.draw();
          player.draw();
          ai.draw();

          var w=4;
          var x= (WIDTH-w)*0.5;
          var y=2;
          var step = HEIGHT/20;
          while(y<HEIGHT){
            ctx.fillRect(x,y+step*0.25,w,step*0.5)
            y+=step;
          }

          ctx.restore();


        }


        // start and run the game
        main();
    </script>
</body>

</html>

2 个答案:

答案 0 :(得分:2)

你有两个问题:

  1. 绘制数字时,不会删除之前已打印的数字。也就是说,当分数变为1时,您在已渲染的0上呈现1 顶部。最简单的解决方法是执行fillRect并在之前绘制黑色矩形在你画一个新分数之前的书面分数。

  2. 当你解决这个问题时,你会注意到你的分数永远不会超过1.原因是代码中的拼写错误增加了它,替换

  3. computerCount =+1;
    

    computerCount += 1;
    

答案 1 :(得分:0)

@Ishamael提到,第139行的计算机数量需要更改为computerCount += 1; //After this if statement add if the player scores.

第221行,

function draw(){
    ctx.fillStyle = "black";
    ctx.fillRect(0,0,WIDTH,HEIGHT);
    ctx.save();
    ctx2.fillStyle = "black";
    ctx2.fillRect(0,0,WIDTH, 100);
    ctx2.save();
    ctx2.fillStyle = "red";
    ctx2.font = "bold 40px monaco";
    ctx2.fillText(String(computerCount),100,100);
    ctx2.fillText("VS",120,100);
    ctx2.fillText(String(playerCount),175,100);
    ctx2.save();
    ctx.fillStyle = "white";
    . . .
}

记住你的分号并在写作之前设置文字样式。我还添加了重绘以删除以前的记分板。