2013-10-20 72 views
1

我想使用HTML5 Canvas和Javascript制作游戏。我想要做的是在特定的时间间隔周围在屏幕上移动一只瓢虫。当鼠标悬停在瓢虫上时,它会增加间隔并在不同的地方产卵。现在我拥有它,所以当你刷新页面时,瓢虫会在不同的地方产生。我不知道如何使它自己更新或如何让它检测鼠标悬停。HTML5画布游戏产卵间隔

谢谢你提前。

这是我到目前为止有:

<!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> 
+0

问题是什么? – Thew

回答

0

第一。自行更新。

为了让错误在屏幕上移动,应定期用更新:

// 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 
} 

PS:

有很多讨厌的框架在那里了帆布和操作HTML和dom。他们让生活更轻松。但在探索它们之前,在纯粹的JS中做这件事很好。

+0

谢谢你,这帮了我。 如果我想这样做,我只是点击图像,它显示了一个警告,我会怎么做? – justinC19

+0

@ justinC19你可以使用'onmousedown'和'onmouseup'事件。就像'onmousemove'一样。 – Waterlink