html 帆布弹跳球,javascript

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html 帆布弹跳球,javascript相关的知识,希望对你有一定的参考价值。

<html>
   <head>
      <style type="text/css">
      canvas{ border:#666 1px solid;}
      </style>
      <script type ="application/javascript" language="javascript">
         var canvas;
         var ctx;
         var dx = 1;
         var dy = 2;
         var bar = new Bar(400, 500);
         var circle = new Circle(400, 30, 10);
         var dxBar = 6;
         var timer;
         var barImg;

         function Bar(x, y) {
            this.x = x;
            this.y = y;
         }

         function Circle(x, y, r) {
            this.x = x;
            this.y = y;
            this.r = r;
         }

         function drawBall(c) {
            ctx.beginPath();
            ctx.arc(c.x, c.y, c.r, 0, Math.PI * 2, true);
            ctx.fill();
         }

         function doKeyDown(e) {
            if (e.keyCode == 37) {
               if (bar.x - dxBar > 0)
                  bar.x -= dxBar;
            } else if (e.keyCode == 39) {
               if (bar.x + dxBar < canvas.width)
                  bar.x += dxBar;
            }
         }

         function init() {
            window.addEventListener("keydown", doKeyDown, false);
            barImg = document.getElementById("bar");
            canvas = document.getElementById("canvas");
            ctx = canvas.getContext("2d");
            timer = setInterval(draw, 10);
            return timer;
         }

         function draw() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = "#FAF7F8";
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = "#003300";
            drawBall(circle);
            if (circle.x + dx > canvas.width || circle.x + dx < 0)
               dx = -dx;
            if (circle.y + dy > bar.y && circle.x > bar.x && circle.x < bar.x + barImg.width)
               dy = -dy;
            if (circle.y + dy > canvas.height || circle.y + dy < 0)
               dy = -dy;
            circle.x += dx;
            circle.y += dy;
            ctx.drawImage(barImg, bar.x, bar.y);
            if (circle.y > bar.y) {
               clearTimeout(timer);
               ctx.clearRect(0, 0, canvas.width, canvas.height);
               alert("Game Over");
            }
         }
      </script>
   </head>
   <body onload="init();">
      <div>
         <canvas id="canvas" width="800" height="600">
         Sorry, browser does not support canvas.
         </canvas>
      </div>
      <img src="bar.png" id="bar" style="display:none"/>
   </body>
   </html>

以上是关于html 帆布弹跳球,javascript的主要内容,如果未能解决你的问题,请参考以下文章

我如何在重力作用下弹回球?

Clojurescript:制作弹跳球的功能性方法

html 弹跳球

OpenJudge百炼习题解答(C++)--题3142:球弹跳高度的计算

SkiaSharp 之 WPF 自绘弹跳球(案例版)

翻译《向“弹跳球”演示程序添加新功能》 in MDN