canvas- play billiards

First, the idea

  1. Draw billiards chopping board
  2. Painted ball method
  3. Ball moves together with the operation (control transparency)
  4. Mouse clicks, the ball began firing, uniform (actually there is friction, to reduce speed), met chopping board to return, every time displacement speed or distance
  5. Moving the mouse to place the position of the ball
  6. Mouse out, stop action

Second, the code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>controlBall</title>
</head>
<body>
    <canvas id="canvas" width="600" height="300"></canvas>

    <script>
      var canvas = document.getElementById('canvas');
      var ctx = canvas.getContext('2d');
      var raf;
      var running = false;


      // 绘制边框
      function drawRect() {
        ctx.beginPath();
        ctx.rect(0,0,canvas.width,canvas.height);
        ctx.strokeStyle = '#000';
        ctx.stroke();
      }

      var ball = {
        x: 100,
        y: 100,
        vx: 5,
        vy: 1,
        radius: 25,
        color: 'blue',
        draw: function() {
          ctx.beginPath();
          ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
          ctx.closePath();
          ctx.fillStyle = this.color;
          ctx.fill();

        }
      };

      function clear() {
        ctx.fillStyle = 'rgba(255,255,255,0.3)';
        ctx.fillRect(0,0,canvas.width,canvas.height);
      }

      function draw() {
        clear();
        drawRect();
        ball.x += ball.vx;
        ball.y += ball.vy;

        if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) {
          ball.vy = -ball.vy;
        }
        if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) {
          ball.vx = -ball.vx;
        }

        ball.draw();

        raf = window.requestAnimationFrame(draw);
      }

      canvas.addEventListener('mousemove', function(e){
        if (!running) {
          clear();
          drawRect();
          ball.x = e.clientX;
          ball.y = e.clientY;
          ball.draw();
        }
      });

      canvas.addEventListener('click',function(e){
        if (!running) {
          raf = window.requestAnimationFrame(draw);
          running = true;
        }
      });

      canvas.addEventListener('mouseout', function(e){
        window.cancelAnimationFrame(raf);
        running = false;
      });

      ball.draw();
      drawRect();
    </script>
</body>
</html>

 

Guess you like

Origin www.cnblogs.com/it-cuiyi/p/10978665.html