Javascript HTML5画布游戏生成间隔

Javascript HTML5画布游戏生成间隔,javascript,html,Javascript,Html,我正在尝试使用HTML5画布和Javascript制作一个游戏。我想做的是让一只瓢虫以特定的间隔在屏幕上移动。当鼠标悬停在瓢虫上时,它会增加间隔并在不同的地方产卵。现在我有了它,所以当你刷新页面时,瓢虫会在不同的地方繁殖。我不知道如何让它自己更新或者如何让它检测鼠标悬停 先谢谢你 这就是我到目前为止所做的: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title&

我正在尝试使用HTML5画布和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>
首先。自己更新它

要使bug在屏幕上移动,应使用定期更新:

// instead of update() use setInterval(update, 1000 / FPS)
//update();
setInterval(update, 1000 / FPS);
其中,1000=1秒,1000/FPS=每秒的运行速度。您可以在浏览器控制台中检查它是否每秒执行30次,方法是将日志记录添加到更新:

function update(){
  console.log("Here we go");
}
但要小心:这会严重影响你的浏览器控制台

在这里,您应该从画布上删除旧bug,重新计算坐标并在新位置绘制新的

下一件事是去修复你的背景。将背景函数重命名为DruckGround或其他名称,因为您有一个错误:背景已经定义,它是一个图像

第二。探测悬停

要检查用户是否悬停在bug上,应使用画布上的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做几次是很好的。

问题是什么?谢谢你,这对我很有帮助。如果我想这样做,那么我只需单击图像,它就会显示一个警报,我该怎么做?@justinC19您可以使用onmousedown和onmouseup事件。与onmousemove一样。