Friday, February 4, 2011

ActionScript 3 QuickTip #5: The Graphics API


In Flash 8 there were a bunch of properties and methods of the MovieClip class that allowed us to dynamically draw things at runtime. In ActionScript 3, we have these same capabilities along with some handy new ones. The drawCircle() and drawRoundRect() methods are two which will definitely save Flash devlopers quite a bit of time. The biggest difference in the AS 3 drawing API is that it is now its own class called Graphics and is attached to display objects such as MovieClip, Sprite, and Shape. You access the methods by writing something such as myClip.graphics.lineStyle(). The example below draws a line with a random color wherever your mouse moves. You can click the movie to clear the accumulated graphics. The AS 3 code is listed below that.
  1. clip.addEventListener(MouseEvent.MOUSE_MOVE, drawLine);
  2. clip.addEventListener(MouseEvent.CLICK, clearIt);
  3.  
  4. function drawLine(args:MouseEvent)
  5. {
  6.         clip.graphics.lineStyle(15Math.random()*0xBBD9F7);
  7.         clip.graphics.lineTo(args.localX, args.localY);
  8. }
  9.  
  10. function clearIt(args:MouseEvent)
  11. {
  12.         clip.graphics.clear();
  13. }

No comments:

Post a Comment