EaselJS: Using HitTest

Synopsis: Using the DisplayObject.hitTest method with globalToLocal and localToLocal.
Topics: hitTest, globalToLocal, localToLocal, hit detection
Target: EaselJS v0.6.0

This tutorial is part of the EaselJS GitHub repository.
Check out the repository for more tutorials and a handful of helpful samples.

hitTest

The hitTest method checks a specified point in a display object and returns true if that point is not fully transparent (ie. if it will draw to that pixel). This can be used for checking if a specific object is under the mouse and hit detection.

The following demo calls circle.hitTest(stage.mouseX, stage.mouseY) to determine if the mouse is over the red circle.

This simple implementation works fine when the circle hasn't been moved or transformed, but hitTest expects the position passed to it to be in the local coordinate space. The stage.mouseX and stage.mouseY position is a global (stage) coordinate. To see this behaviour, try changing the circle.x in the hitTest.html example file.

globalToLocal

To convert a global position into a local one, we can use the globalToLocal method. This method takes a global x & y value, and returns an object with x & y properties that have been transformed using the target object's concatenated transformation (ie. including its parent transformations).

This code converts the stage mouse position into a local position and outputs it to the console. The demo below applies this same code to check when transformed shapes are under the mouse. Check out the source in globalToLocal.html to see how it was done.

localToLocal

The globalToLocal method works great if we're checking a stage position, but what about if you want to check hitTest against a point in another transformed object?

You could use localToGlobal and then its counterpart globalToLocal to convert the point from one object's coordinate space to another's, but the localToLocal method does the same thing with a little less code.

The following example show this being used to convert a position (100,0) on a rotating arm into a position relative to a target shape, to show when that point intersects the target. Check out localToLocal.html to see how it works.