I
I
Ilya Reznik2017-07-29 14:22:43
JavaScript
Ilya Reznik, 2017-07-29 14:22:43

How to make the ball bounce off the borders of the "canvas"?

How to make the ball bounce off the borders of the "canvas"?

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Keyboard input</title>
</head>
<body>
  <canvas id="canvas" width="200" height="200"></canvas>
  <script src="https://code.jquery.com/jquery-2.1.0.js"></script>
  <script type="text/javascript">
  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');
  var  width = canvas.width;
  var height = canvas.height;

    var circle = function (x, y, radius, fillCircle) {
      ctx.beginPath();
      ctx.arc(x, y, radius, 0, Math.PI * 2, false);
      if (fillCircle) {
        ctx.fill();
      } else {
        ctx.stroke();
      }
    };

    var Ball = function () {
      this.x = width / 2;
      this.y = height / 2;
      this.xSpeed = 5;
      this.ySpeed = 0;
    };

    Ball.prototype.move = function() {
      		this.x += this.xSpeed;
      		this.y += this.ySpeed;
      		if (this.x < 0) {
      			this.x = width;
      		} else if (this.x > width) {
      			this.x = 0;
      		} else if (this.y < 0) {
      			this.y = height;
      		} else if (this.y > height) {
      			this.y = 0;
      		}
    	};

    	Ball.prototype.draw = function () {
    		circle(this.x, this.y, 10, true);
    	};

    	Ball.prototype.setDirection = function(direction) {
    		if (direction === "up") {
    			this.xSpeed = 0;
    			this.ySpeed = -5;
    		} else if (direction === "down") {
    			this.xSpeed = 0;
    			this.ySpeed = 5;
    		} else if (direction === "left") {
    			this.xSpeed = -5;
    			this.ySpeed = 0;
    		} else if (direction === "right") {
    			this.xSpeed = 5;
    			this.ySpeed = 0;
    		} else if (direction === "stop") {
    			this.xSpeed = 0;
    			this.ySpeed = 0;
    		}
    	};

    	var ball = new Ball;

    	var keyActions = {
    		32: "stop",
    		37: "left",
    		38: "up",
    		39: "right",
    		40: "down"
    	};

    	$("body").keydown(function (event) {
    		var direction = keyActions[event.keyCode];
    		ball.setDirection(direction);
    	});

    	setInterval(function () {
    		ctx.clearRect(0, 0, width, height);
    		ball.draw();
    		ball.move();
    		ctx.strokeRect(0, 0, width, height)
    	}, 30);
  </script>
</body>
</html>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2017-07-29
@iliareznik

Ball.prototype.move = function() {
    this.x += this.xSpeed;
    this.y += this.ySpeed;
    if (this.x < 0 || this.x > width) {
      this.xSpeed *= -1;
      this.x += this.xSpeed * 2;
    }
    if (this.y < 0 || this.y > height) {
      this.ySpeed *= -1;
      this.y += this.ySpeed * 2;
    }
  };

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question