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:
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 mousedblclick
: The user double-clicks the mousemousedown
: The user clicks the mousemouseout
: The user moves the mouse pointer away from an objectmouseover
: The user moves the mouse pointer over an objectpressmove
: The user clicks the mouse and then moves itpressup
: The user releases the mouse either over or outside the objectrollout
: The user rolls away from a child elementrollover
: The user rolls over a child elementFor more details, refer to http://www.createjs.com/Docs/EaselJS/classes/DisplayObject.html#events.
18.220.245.233