Accessibility

ActionScript cookbook beta

Dynamically create and draw on a MovieClip

Problem Summary

You need to dynamically create a MovieClip, place it on the Stage, and draw on it.

Solution Summary

Use the MovieClip constructor to create the MovieClip and then draw into its graphics property.

Explanation

ActionScript 2

function drawCircle(target_mc:MovieClip, radius:Number, fillColor:Number, fillAlpha:Number)
{
   var x:Number = radius;
   var y:Number = radius;
   
   with (target_mc)
   {
      beginFill(fillColor, fillAlpha);
      moveTo(x + radius, y);
      curveTo(radius + x, Math.tan(Math.PI / 8) * radius + y, Math.sin(Math.PI / 4) *
         radius + x, Math.sin(Math.PI / 4) * radius + y);
      curveTo(Math.tan(Math.PI / 8) * radius + x, radius + y, x, radius + y);
      curveTo(-Math.tan(Math.PI / 8) * radius + x, radius+ y, -Math.sin(Math.PI / 4) *
         radius + x, Math.sin(Math.PI / 4) * radius + y);
      curveTo(-radius + x, Math.tan(Math.PI / 8) * radius + y, -radius + x, y);
      curveTo(-radius + x, -Math.tan(Math.PI / 8) * radius + y, -Math.sin(Math.PI / 4) *
         radius + x, -Math.sin(Math.PI / 4) * radius + y);
      curveTo(-Math.tan(Math.PI / 8) * radius + x, -radius + y, x, -radius + y);
      curveTo(Math.tan(Math.PI / 8) * radius + x, -radius + y, Math.sin(Math.PI / 4) *
         radius + x, -Math.sin(Math.PI / 4) * radius + y);
      curveTo(radius + x, -Math.tan(Math.PI / 8) * radius + y, radius + x, y);
      endFill();
   }
}

createEmptyMovieClip("circle_mc", 10);
circle_mc._x = 250;
circle_mc._y = 250;

drawCircle(circle_mc, 250, 0xFFe0AC, 50);

ActionScript 3

var clip:MovieClip = new MovieClip();

addChild(clip);

clip.x = 250;
clip.y = 250;

clip.graphics.lineStyle(2, 0xF89950);
clip.graphics.beginFill(0xFFe0AC, .5);
clip.graphics.drawCircle(0, 0, 200);

Note: In ActionScript 2 drawing is done directly on the MovieClip, whereas in ActionScript 3, it is done on the graphics property of the MovieClip.