Reputation: 13
I'm new to Javascript and I'm using HTML5 canvas in the Dreamweaver editor. I have looked at other posts about mouse events but none seems to tackle my problem.
I am creating a game called 'Click Only Corn bubbles' where items fall and the player moves the mouse to click the corn bubbles but if they click anything else its game over.
So far I have used:
window.addEventListener("keydown",eventKeyDown,false);
window.addEventListener("keyup",eventKeyUp,false);
window.addEventListener("mousedown",onDown,false);
window.addEventListener("mouseup",onUp,false);
window.addEventListener("mousemove",onMove,false);
How do I call these so that they are true? Also how do I make them clickable so I am able to click on the images as they fall?
Upvotes: 1
Views: 1869
Reputation: 11551
First of all we need to find somehow where the mouse cursor is located. Here is a function to get the mouse coordinates:
function getMousePosition(e) {
var x, y;
x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - canvas.offsetLeft;
y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop - canvas.offsetTop;
return {
get x() { return x },
get y() { return y }
}
}
HTMLCanvasElement.prototype.getMousePosition = getMousePosition;
Then we need to test if the mouse has been clicked and if yes locate the mouse and the images coordinates. If the mouse coordinate is overlapping the image coordinate then do something. We can test the condition like in the following method:
var isMouseDown = false;
function onDown(e) {
var pos = {x:0, y:0 };
isMouseDown = true;
var mouseCoordinate = getMousePosition(e);
for (var i = 0; i < images.length; i++) {
var bubble = images[i];
if (( mouseCoordinate.x > image.x && // get the image most left position
mouseCoordinate.x < image.x + image.size) && // get image most right position
( mouseCoordinate.y > image.y &&
mouseCoordinate.y < image.y + image.size)) {
index = image.indexOf(image, 0);
pos.x = mouseCoordinate.x;
pos.y = mouseCoordinate.y;
break;
}
}
}
if (isMouseDown &&
pos.x < image[index].x + image[index].size &&
pos.x > image[index].x &&
pos.y < image[index].y + image[index].size &&
pos.y > image[index].y)
// if the condition is true, then do something
function onUp(e) {
isMouseDown = false;
}
You can see the live example here: http://hellopixel.net/experiments/404/404.html
Upvotes: 0
Reputation: 573
May be this would be helful.
document.addEventListener('click',mouseClick,false);
function mouseClick(e)
{
mouseX = e.pageX - canvas.offsetLeft;
mouseY = e.pageY - canvas.offsetTop;
//Now mouseX and mouseY contains the x and y location of mouse click event but w.r.t. your canvas location .
}
Upvotes: 2