IFraim
@IFraim
Web-Developer

Как сделать так, чтобы объект не выходил за границы 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>
  • Вопрос задан
  • 1043 просмотра
Решения вопроса 1
0xD34F
@0xD34F Куратор тега JavaScript
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));
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы