I
I
IFramex2019-10-08 12:13:48
JavaScript
IFramex, 2019-10-08 12:13:48

How to make sure that the object does not go beyond the boundaries of the canvas?

<!DOCTYPE html>
<html lang="ru">
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="style.css">
  <title>game</title>
</head>
<body>
  <canvas id="canvas" width="800px" height="600px"></canvas>
  <script type="text/javascript">
    var canvas = document.getElementById('canvas');
    console.log(canvas);

    var ctx = canvas.getContext('2d');
    console.log(ctx);

    // ширина
    var W = canvas.width;
    // высота
    var H = canvas.height;
    // фпс
    var FPS = 30;

    function Player() {
      this.x = W / 2; // по 400 ширине
      this.y = H / 2; // по 300 высоте
      this.w = 60; // ширина объекта
      this.h = 60; // длина объекта
      this.dx = 0;
      this.dy = 0;
      this.speed = 10; // скорость объекта

      // устанавливает движение объекта
      this.update = () => {
        this.x += this.dx;
        this.y += this.dy;
      }
      // рисует объект
      this.draw = () => {
         ctx.fillStyle = 'rgb(64, 97, 214)';
         ctx.fillRect(this.x - this.w / 2, this.y - this.h / 2, this.w, this.h);
      }
    }
    // создает нового объекта
    var pl = new Player();


    function draw() {
      // очищает фигуру за собой
      ctx.clearRect(0, 0, W, H);

      pl.update();
      pl.draw();
    }

    // обновление чистоты кадров
    setInterval(draw, 1000 / FPS);

    document.addEventListener('keydown', event => {
      // если нажата правая кнопка стрелки 
      if (event.key == 'ArrowRight') {
        pl.dx = pl.speed;
      }
      // если нажата левая кнопка стрелки
      else if (event.key == 'ArrowLeft') {
        pl.dx = -pl.speed;
      }
    });

    document.addEventListener('keydown', event => {
      if (event.key == 'ArrowUp') {
        pl.dy = -pl.speed;
      }
      else if (event.key == 'ArrowDown') {
        pl.dy = pl.speed;
      }

    });

    document.addEventListener('keyup', event => {
      // если правая кнопка стрелки опущена
      if (event.key == 'ArrowRight') {
        pl.dx = 0;
      }
      else if (event.key == 'ArrowLeft') {
        // если левая кнопка стрелки опущена
        pl.dx = 0;
      }

    });

    document.addEventListener('keyup', event => {
      if (event.key == 'ArrowUp') {
        pl.dy = 0;
      }
      else if (event.key == 'ArrowDown') {
        pl.dy = 0;
      }

    });
  </script>
</body>
</html>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-10-08
@IFraim

this.update = () => {
  const
    w = this.w / 2,
    h = this.h / 2;

  this.x = Math.max(w, Math.min(W - w, this.x + this.dx));
  this.y = Math.max(h, Math.min(H - h, this.y + this.dy));
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question