javascript - 如何更新写在 Canvas 上的文本

标签 javascript html canvas

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

Screenshot of the Pong game

JSFiddle format - 您可以通过在 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>

最佳答案

你有两个问题:

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

  2. 当你解决这个问题时,你会注意到你的分数永远不会超过 1。原因是代码中的错字导致它递增,替换

computerCount =+1;

computerCount += 1;

关于javascript - 如何更新写在 Canvas 上的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34365219/

相关文章:

javascript - HTML5 Canvas globalCompositeOperation 更轻,同时在源码之上

javascript - HTML5 游戏刷新率与 requestAnimationFrame

javascript - 如何分别控制两个嵌入的 iframe youtube 视频?

javascript - 由 google charts js 提供的自定义圆环图

html - CSS Column-Count 结合 hidden

html - 带有 CSS 的灯泡按钮

javascript - 使用固定标题的表标题列不保持宽度

javascript - YQL 天气声明未显示某些物体,例如日出、日落和风寒

javascript - 带有页眉和页脚的双动画模态

javascript - 如何缩放 Canvas 并保持其在屏幕上的位置?