1

How can I get the coordinates of the cursor on the screen properly ?

I tried using event.clientX and event.clientY however it only works in certain cases . If I try to make a special function for it it works

 stage = new createjs.Stage("myCanvas");
 circle = new createjs.Shape();
 circle.graphics.beginFill("red").drawCircle(0, 0, 40);
 createjs.Ticker.addEventListener("tick", handleTick);

 function handleTick() {
     if (circle.x > stage.canvas.width) { circle.x = 0; }
     stage.addChild(circle);
     stage.update();
 }

 document.addEventListener("mousemove", function(){circle.x = event.clientX,circle.y = event.clientY});

However when I try to include it in my function handleTick() I get a thon of erros :

Uncaught TypeError: Cannot read property 'clientX' of undefined

Are there any other things I can use for this ? And why don't it work in my the handleTick() function ?

Ionut Eugen
  • 481
  • 2
  • 6
  • 27

1 Answers1

1

addEventListener should provide the event for you, if you do like this, and add event as a function argument. With that you should be able to get the mouse position and assign its values to your circle object.

function handleTick(event) {
     circle.x = event.clientX;
     if (circle.x > stage.canvas.width) { circle.x = 0; }
     stage.addChild(circle);
     stage.update();
}

If it won't, then you need to capture the mouse move and store its values in a global variable, and here is a great post showing additional ways how to do that.

Asons
  • 84,923
  • 12
  • 110
  • 165