我正在尝试使用 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");
}
但要小心:这会严重影响您的浏览器控制台。
在这里,您应该从 Canvas 中删除旧的错误,重新计算坐标并在新位置绘制新的错误。
下一步是修复你的背景。将您的 background
函数重命名为 drawBackground
(或其他名称),因为您遇到错误:背景已定义,并且它是一个图像。
第二。检测悬停。
要检查用户是否将鼠标悬停在错误上,您应该在 Canvas 上使用 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:
有很多令人讨厌的 Canvas 框架以及操作 html 和 dom 的框架。它们让生活变得更轻松。但在探索它们之前,最好先用纯 JS 来做几次。
关于javascript - HTML5 Canvas 游戏生成间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19479996/