0

我试图让行星在点击时发出警报消息。问题是,据我测试,onmousedown 仅适用于画布。行星代码:

var planets = [];
for (var b=0;b<3;b++) {
planets.push(planet(0,360,Math.random()*600,Math.random()*600));
}

function planet(I,shiips,xpos,ypos){
I = I||{};
I.ships = shiips;
I.x=xpos;
I.y=ypos;
return I;
}

点击检测代码;测试行星物体和图像

update = function(){
planetImage.onmousedown=function(){alert("works!")};
planets[0].onmousedown=function(){alert("works!")};
}
setInterval(update,100);

我使用画布绘制图像,如果有帮助的话。我发现以下代码给出了鼠标位置,但它对我不起作用:

(function() {
    var mousePos;

    window.onmousemove = handleMouseMove;
    setInterval(getMousePosition, 100); // setInterval repeats every X ms

    function handleMouseMove(event) {
        event = event || window.event; // IE-ism
        mousePos = {
            x: event.clientX,
            y: event.clientY
        };
    }

    function getMousePosition() {
        var pos = mousePos;
        if (!pos) {
            // We haven't seen any movement yet
        }
        else {
            // Use pos.x and pox.y
        }
    }
})();

我试图保持简单,我不太喜欢 jquery 或任何复杂的东西。再次:问题是 onmousedown 仅适用于画布对象,即

canvas.onmousedown=function(){alert("works!")};
4

1 回答 1

0

我现在可以使用以下代码:

update = function(){
canvas.onmousedown=function(){
var e = window.event;
var posX = e.clientX;
var posY = e.clientY;
alert("X position: "+ posX + " Y position: " + posY);
};
setInterval(update,100);
于 2015-05-21T14:17:43.020 回答