canvas 平抛运动

2018-11-26  本文已影响0人  千叶ranck
<html>
  <head>
  <style>
  * {
    padding: 0;
    margin: 0;
  }
  canvas {
    display: block;
    margin: 80px auto;
    border: 1px solid #ddd;
  }
  </style>
  </head>
  <body>

    <canvas id="canvas" width="800" height="600"></canvas>
  </body>
  <script>
    var canvas = document.querySelector('#canvas')
    var ctx = canvas.getContext('2d')
    var timer
    ctx.font="30px Arial";

    function Ball (x,y,r,t,color) {
      this.x = x
      this.y =y
      this.r = r
      this.t = t
      this.color = color
    }

    Ball.prototype.render = function () {
      ctx.beginPath();
      ctx.fillText('平抛运动', 100,100)

      ctx.arc(this.x,this.y ,this.r,0,2*Math.PI);
      ctx.fill()
    }

    Ball.prototype.horizontal = function (vx) {
      this.x += vx
    }

    Ball.prototype.vertical = function (g) {
      if (this.y< 500 ) {
        var t = this.t
        this.t++
        this.y = g*t*t + this.y
      } else {
        clearInterval(timer)
      }

    }

    var ball = new Ball(30, 30, 24, 0.5, '#f90')
    console.dir(ctx)
    timer = setInterval(function () {

      ctx.clearRect(0,0,800,600)
      ball.render()
      ball.horizontal(36)
      ball.vertical(0.2)
    }, 30)

  </script>
</html>

上一篇下一篇

猜你喜欢

热点阅读