HTML5 画布游戏生成间隔

HTML5 canvas game spawn interval

本文关键字:游戏 布游戏 HTML5      更新时间:2023-09-26

我正在尝试使用HTML5 Canvas和Javascript制作游戏。我想做的是让瓢虫以特定的间隔在屏幕上移动。当鼠标悬停在瓢虫上时,它会增加间隔并在不同的地方生成。现在我有了它,所以当你刷新页面时,瓢虫会在不同的地方生成。我不知道如何让它自行更新或如何让它检测鼠标悬停。

提前谢谢你。

这是我到目前为止所拥有的:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<canvas id="myCanvas" width="600" height="480"></canvas>
<script>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');
  var posX = (Math.random() * 520) + 1;
  var posY = (Math.random() * 400) + 1;
  var ladybug = new Image();
  var background = new Image();
  var velocity = 5;
  var FPS = 30;
  update();
  draw();
  background();
  function background() {
      background.onload = function () {
          context.drawImage(background, 50, 50);
      }
      background.src = 'Images/grass.png';
  }
  function draw() {
      context.clearRect(0, 0, myCanvas.width, myCanvas.height);
      context.fillStyle = "black"; // Set color to black
      context.font = "bold 16px Arial";
      context.fillText("Sup Bro!", posX, posY);
      ladybug.onload = function () {
          context.drawImage(ladybug, posX, posY);
      };
      ladybug.src = 'Images/Ladybug.png';
  }
  function update() {

  }
</script>

</body>
</html>

第一。自行更新它。

要使错误在屏幕上移动,您应该使用定期更新:

// instead of update() use setInterval(update, 1000 / FPS)
//update();
setInterval(update, 1000 / FPS);

其中 1000 = 1 秒,1000 / FPS = 每秒运行 FPS。您可以在浏览器控制台中检查它是否每秒执行 30 次,方法是添加日志记录进行更新:

function update(){
  console.log("Here we go");
}

但要小心:这会给您的浏览器控制台发送垃圾邮件。

在这里,您应该从画布上擦除旧错误,重新计算坐标并在新位置绘制新坐标。

接下来就是去修复你的背景。将background函数重命名为drawBackground(或其他),因为您有一个错误:背景已经定义并且它是一个图像。

第二。检测悬停。

要检查用户是否将鼠标悬停在错误上,您应该在画布上使用 onmousemove 事件:

function init() {
  canvas.onmousemove = function(event) {
    if (window.event) event = window.event; // IE hack
    var mousex = event.clientX - canvas.offsetLeft;
    var mousey = event.clientY - canvas.offsetTop;
    mousemove(mousex, mousey);
  }
}
function mousemove(x, y) {
  console.log (x, y);
  // here check, if mousex and mousey is in rectangle (x, y, x + width, y + width)
  // where x, y, width and height are parameters of lady bug
}

附注:

有很多

令人讨厌的框架用于画布和操作html和dom。它们使生活更轻松。但是在探索它们之前,最好在纯JS中进行几次。