Transparent copyPixels()

Actionscript:
  1. var canvas:BitmapData=new BitmapData(400,400,true,0x000000);
  2. var eraser:BitmapData=new BitmapData(400,400,true,0x00000000);
  3. addChild(new Bitmap(canvas));
  4. var redOval:Shape = new Shape();
  5. with(redOval.graphics) lineStyle(0,0), beginFill(0xFF0000), drawEllipse(0,0,10,50);
  6.  
  7. // draw a background to emphasize transparency
  8. createBackground();
  9.  
  10. addEventListener(Event.ENTER_FRAME, onLoop);
  11.  
  12. function onLoop(evt:Event):void {
  13.     // clear canvas so that it is completely transparent
  14.     canvas.copyPixels(eraser, eraser.rect, new Point(0,0), eraser);
  15.     redOval.x = mouseX;
  16.     redOval.y = mouseY;
  17.     redOval.rotation += 10
  18.     // transform.matrix contains all transformation information for
  19.     // the redOval including scaleX, scaleY, x, y, rotation etc...
  20.     canvas.draw(redOval, redOval.transform.matrix);
  21. }
  22.  
  23. function createBackground():void {
  24.     for (var i:int = 0; i<100; i++){
  25.         with(graphics) lineStyle(0,0x000000), lineTo(Math.random()*400, Math.random()*400);
  26.     }
  27. }

This example builds on yesterdays snippet. Instead of just allowing the red oval to be continuously drawn to the canvas BitmapData... in this example the canvas BitmapData is erased again and again before the red oval is drawn to it. To erase it with a flat color you might use BitmapData.fillRect() but if you want to erase it so that it is completely transparent you need to use BitmapData.copyPixels():

Actionscript:
  1. canvas.copyPixels(eraser, eraser.rect, new Point(0,0), eraser);

The eraser BitmapData is a completely transparent BitmapData object. The key here is the fourth argument.... "alphaBitmapData".This is what causes the canvas BitmapData to become completely transparent again at the beginning of each enterFrame.

This argument is separate from the first argument (sourceBitmapData) for added flexibility.

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

2 Comments

  1. Posted October 1, 2009 at 12:49 am | Permalink

    So, when attaching the dataobject to a movieclip, how can you clear out the graphics that already exist in that clip? I’ve tried fillRect, graphics.clear(), but my images with alpha just pile up on top of each other as I attach them.

  2. Posted October 1, 2009 at 8:32 am | Permalink

    if i understand you correctly you need to use the displaylist:

    while( myClip.numChildren > 0){
    myClip.removeChild(myClip.getChildAt(0));
    }

Post a Comment

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

*
*