创建鼠标事件以单击html5中的图像

时间:2012-10-11 19:23:55

标签: javascript-events html5-canvas

嗨,我是javascript中的新手,我在Dreamweaver编辑器中使用HTML5画布。我查看了有关鼠标事件的其他帖子,但似乎没有一个可以解决我的问题。

我正在制作一款名为“Click Only Corn bubbles”的游戏,其中物品掉落,玩家移动鼠标点击玉米泡,但如果他们点击其他任何游戏结束。

到目前为止,我已经使用过:

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);  

我如何称呼它们以使它们成立?另外我如何使它们可点击以便我可以在图像落下时点击

2 个答案:

答案 0 :(得分:2)

可能会有所帮助。

 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 .
 }

答案 1 :(得分:0)

首先,我们需要找到鼠标光标所在的位置。这是一个获取鼠标坐标的函数:

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;

然后我们需要测试鼠标是否已被点击,如果是,则找到鼠标和图像坐标。如果鼠标坐标与图像坐标重叠,则执行某些操作。我们可以像以下方法一样测试条件:

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;
}

您可以在此处查看实时示例:http://hellopixel.net/experiments/404/404.html