在CodePen我的代码链接- http://codepen.io/PartTimeCoder/pen/RaMZop?editors=0010
Javascript下方,在增加功能中,有一个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);
这样做与鼠标触摸红点时是一样的,但是它将在鼠标离开画布时显示该消息。你去!
这是工作版本的示例代码笔:避免出现红点
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句