Better BitmapData Brush

Actionscript:
  1. var canvas:BitmapData = new BitmapData(stage.stageWidth,stage.stageHeight,false, 0xCCCCCC);
  2. addChild(new Bitmap(canvas));
  3. var prevX:Number;
  4. var prevY:Number;
  5. var brush:Shape = new Shape();
  6.  
  7. stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
  8. stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
  9. function onDown(evt:MouseEvent):void{
  10.     prevX = mouseX;
  11.     prevY = mouseY;
  12.     addEventListener(Event.ENTER_FRAME, onLoop);
  13. }
  14.  
  15. function onUp(evt:MouseEvent):void{
  16.     removeEventListener(Event.ENTER_FRAME, onLoop);
  17. }
  18.  
  19. function onLoop(evt:Event):void {
  20.       brush.x = mouseX;
  21.       brush.y = mouseY;
  22.       with (brush.graphics){
  23.           clear();
  24.           lineStyle(3, 0x000000);
  25.           lineTo(prevX-mouseX, prevY-mouseY);
  26.       }
  27.       canvas.draw(brush, brush.transform.matrix);
  28.       prevX = mouseX;
  29.       prevY = mouseY;
  30. }

If you write a drawing program with the Graphics class alone, you'll notice that eventually the flash player will start to slow down. This could take quite some time, but it will eventually happen. Because the Graphics class is entirely vector based, the flash player needs to keep track of every single point that makes up any line in your drawing. If you draw something and then erase it by drawing white vector lines over it, flash still needs to know about that thing that you erased.

The snippet I wrote yesterday reminded me of the technique used in the above snippet. In yesterdays post every line is drawn using the graphics class. As a result, eventually the flash player begins to choke.

Today's snippet draws a vector between the previous mouse location and the current mouse location - this vector is then drawn onto a BitmapData object and the vector is cleared. So rather than creating vector graphics that are continuously increasing in complexity, your just changing the color of pixels around on a BitmapData.

To see a visual explanation take a look at the below swf. I slowed it down to 5fps, I tinted the vector red and scaled up the stage so you can differentiate between what's vector and what's bitmap:


Click to see the swf...

This entry was posted in BitmapData, Graphics and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Trackback

  1. [...] Better BitmapData Brush [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*