我在 CodePen 中的代码的链接 - http://codepen.io/PartTimeCoder/pen/RaMZop?editors=0010
下面是 Javascript,在 increase 函数中有一个 if 命令可以防止用户的鼠标离开屏幕,但它不起作用。此外,当页面加载时,它应该开始添加分数,但它只在点击后才开始。我看不出有任何理由会发生这种情况:
$(document).ready(function() {
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d")
var height = window.innerHeight
var width = window.innerWidth
var mouse = {};
var hover;
var redDots = 2;
var score = 0;
canvas.width = width
canvas.height = height
var circle_count = 10;
var circles = [];
var generate = function() {
for (var i = 0; i < circle_count; i++) {
circles.push(new circle());
}
}
setInterval(generate, 100);
canvas.addEventListener('mousedown', mousePos, false);
canvas.addEventListener('touch', mousePos, false);
function mousePos(e) {
mouse.x = e.pageX;
mouse.y = e.pageY;
}
function circle() {
this.speed = {
x: 2.5 + Math.random() * 5,
y: 2.5 + Math.random() * 5
}
this.location = {
x: 0 - Math.random() * width,
y: 0 - Math.random() * height
}
this.accel = {
x: -1.5 + Math.random() * 3,
y: -1.5 + Math.random() * 3
}
this.radius = 5 + Math.random() * 10
}
var draw = function() {
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = "black";
ctx.fillRect(0, 0, width, height);
ctx.globalCompositeOperation = "lighter";
for (var i = 0; i < circles.length; i++) {
var c = circles[i];
ctx.beginPath();
ctx.fillStyle = "red";
ctx.arc(c.location.x, c.location.y, c.radius, Math.PI * 2, false);
ctx.fill();
c.speed.x += c.accel.x;
c.speed.y += c.accel.y;
c.location.x += c.speed.x;
c.location.y += c.speed.y;
if (mouse.x > c.location.x - c.radius && mouse.x < c.location.x + c.radius && mouse.y > c.location.y - c.radius && mouse.y < c.location.y + c.radius) {
hover = true;
}
if (hover) {
$("canvas").hide();
$("#message").html("Sorry you lost. You finished with a score of " + score + "!");
}
}
}
setInterval(draw, 33);
var increase = function() {
if (mouse.x > 1 && mouse.y > 1 && !hover) {
score++;
redDots += 25;
$("#score").html("Score - " + score);
console.log(redDots);
}
if (mouse.x > canvas.width || mouse.y > canvas.height || mouse.x < 0 || mouse.y < 0) {
hover = true;
}
}
setInterval(increase, 1000);
});
感谢所有帮助。提前致谢!
最佳答案
您只需要一个mouseout
事件监听器,很简单!
但首先,您需要在 mousemove 上跟踪鼠标,以防止通过先单击来启动游戏。我在下面有一个例子。
canvas.addEventListener('mousemove', mousePos, false);
使用它代替 mousedown
事件监听器。
其次,修复mouseout
时游戏停止的问题。
这是一个例子
canvas.addEventListener('mouseout', function() {
$("canvas").hide();
$("#message").html("Sorry you lost. You finished with a score of " + score + "!");
}, false);
这与鼠标触摸红点时的效果相同,但它会在鼠标离开 Canvas 时显示消息。给你!
这是工作版本的代码笔示例:Avoid The Red Dots
关于javascript - 当光标离开屏幕时,游戏不会以 Javascript 结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36611230/