0

Im trying to make planets that give an alert message when clicked. Problem is, onmousedown only works on canvas, as far I tested. Code for planets:

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

code for click detection; tests both for planet object and the image

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

Im using canvas to draw the images, if that hhelps. I found the following code that gives mouse position, but it doesnt work for me:

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

Im trying to keep it simple, I don't really like jquery or anything complicated. Once again: the problem is onmousedown only works on the canvas object, i.e.

canvas.onmousedown=function(){alert("works!")};
fedorqui
  • 275,237
  • 103
  • 548
  • 598
none
  • 9
  • 2
  • 6
  • 2
    Have you tried comparing the mouse position in the canvas's mouseClick event to the positions of the planets? – jonhopkins Sep 16 '13 at 13:46
  • _"Im trying to keep it simple, I don't really like jquery or anything complicated"_ - Used correctly, jQuery makes things _less_ complicated, not _more_ complicated. _Much_ less complicated for some purposes. – nnnnnn Sep 16 '13 at 13:47
  • What's the result of `alert(planets.length);` ? – gvee Sep 16 '13 at 13:49
  • Probably 3, I made an initialization so at start 3 random planets are created – none Sep 16 '13 at 14:10

1 Answers1

0

I got it working now with this code:

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);
fedorqui
  • 275,237
  • 103
  • 548
  • 598