Working with events

DisplayObject has a method to add events to shapes or objects. Using addEventListener, we can add an event to DisplayObject (for example, shape). This function has two mandatory arguments:

  • The name of the event
  • The callback function for the event

We will understand this method of working with events with the following code:

displayObject.addEventListener("click", handleClick); 
function handleClick(event) {
  // Click happened.
}

In the first line, a click event is added to displayObject so that the handleClick function is called when the user clicks on the object. The handleClick function is empty in this example.

Let's consider our earlier example of the circle and add a click event to our circle. Inside the callback function of the click event, we move the circle 10 pixels to right. Here is the code for that:

circle.addEventListener("click", handleClick); 
function handleClick(event) { 
event.target.x += 10; 
stage.update(); 
}

In the first line, we have our DisplayObject. Using addEventListener, the click event is added to the circle. Our callback handler is handleClick. Inside this function, we can get target objects (the circle shape, in this example) and change properties of the shape (for example, width, height, or position) via the event variable.

event.target is the target shape object. In every callback function call, we add the x property with 10 and then call the update function from the stage object. We have to call the update function after changing properties in order to apply changes.

Remember that to add events to DisplayObject, we need to add an event listener first and then add displayObject to the stage. Here is the complete source code for our example:

var stage = new createjs.Stage("demoCanvas");

var circle = new createjs.Shape();
circle.graphics.beginFill("red").drawCircle(0, 0, 50);
circle.x = 100; 
circle.y = 100; 

circle.addEventListener("click", handleClick); 
function handleClick(event) { 
  event.target.x += 10; 
  stage.update(); 
}
stage.addChild(circle);
stage.update();

EaselJS has many more events, and you can use all of them in the same example explained previously.

Currently DisplayObjects supports the following events:

  • click: The user clicks and releases the mouse
  • dblclick: The user double-clicks the mouse
  • mousedown: The user clicks the mouse
  • mouseout: The user moves the mouse pointer away from an object
  • mouseover: The user moves the mouse pointer over an object
  • pressmove: The user clicks the mouse and then moves it
  • pressup: The user releases the mouse either over or outside the object
  • rollout: The user rolls away from a child element
  • rollover: The user rolls over a child element
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.245.233