我之前曾问过类似的问题,但我没有收到解决方案。
我目前有7个bug从顶部到底部掉线。我希望用户能够点击一个会导致淡出/消失的bug。如果鼠标在图像中,我会需要某种检测,点击将允许它淡出或者没有效果。
这是至关重要的,因为我将包括一个评分系统,每次点击将获得1分,并且每次失误1分将会丢失。
var noOfBugs = 7;
var bug = [];
for(var i =0; i < noOfBugs; i++){
var x = Math.floor(Math.random()*canvas.width);
var y = Math.floor(Math.random()*100);
bug[i] = new Bug(x,y);
}
imageBug = new Image();
imageBug.src = "imgs/redbug.png";
function Bug (x,y){
this.x = x;
this.y =y;
this.drop = function(){
var dir = Math.floor(Math.random())*3;
if(dir == 0){
this.x = this.x;
}
this.y = this.y+1;
if(this.y > canvas.height){
this.y=0;
}
}
this.show = function (){
context.drawImage(imageBug, this.x, this.y)
}
}
function draw (){
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
for(var i=0; i<noOfBugs; i++){
bug[i].show();
bug[i].drop();
}
}
// Mouse click on bug
canvas.onclick = function (event){
var mouseX = event.clientX;
var mouseY = event.clientY;
if (mouseX === x && mouseY === y){
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
context.globalAlpha = 0.1;
context.drawImage(imageBug, this.x, this.y, imageX, imageY);
alert("its a hit");
}
else {
alert("You missed");
score -= 0;
}
}
function reload (){
draw ();
window.requestAnimationFrame(reload);
}
reload();
};
答案 0 :(得分:0)
将此代码用于鼠标:
mouse = {
x: 0,
y: 0,
down: false
};
canvas.addEventListener("mousemove", (event => {
var bounds = canvas.getBoundingClientRect();
// Get mouse position INSIDE canvas.
mouse.x = ((event.clientX - bounds.left) / (bounds.right - bounds.left)) * canvas.width;
mouse.y = ((event.clientY - bounds.top) / (bounds.bottom - bounds.top)) * canvas.height;
if(event.which == 1) { // If mouse was left clicked.
mouse.down = true;
} else {
mouse.down = false;
}
}));
canvas.addEventListener("mousedown", (event => {
if(event.which == 1) { // If mouse was left clicked.
mouse.down = true;
} else {
mouse.down = false;
}
}));
canvas.addEventListener("mouseup", (event => {
mouse.down = false; // If mouse click was released.
}));
由于鼠标是2d点,而bug是2d矩形,你可以使用这个点对点功能:
function dotInBox(point, rect) {
return (
point.x > rect.x &&
point.x < rect.x + rect.width &&
point.y > rect.y &&
point.y < rect.y + rect.height
);
}
point
将是mouse
,rect
将是表示错误边界框的对象。
为了淡出错误,我建议您使用context.globalAlpha
。您可以在https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalAlpha找到它的文档。
只需将此伪造代码与其他代码段一起使用即可!
if mouse is down:
for var i = 0. i < length of bugs. increment i:
if mouse touching current bug:
make current bug fade.
in update loop:
for var i = 0. i < length of bugs. increment i:
if bug is fading:
lower current bug’s opacity.
if bug is completely faded:
delete current bug.
decrement i. (since the bug was removed, you would accidentally skip a bug)